I have a templated function for returning the number of digits in a number:
template <typename R>
static inline unsigned count(const R num)
{
if(num < 10) return 1;
else if (num < 100) return 2;
else if (num < 1000) return 3;
else if (num < 10000) return 4;
else if (num < 100000) return 5;
else if (num < 1000000) return 6;
else if (num < 10000000) return 7;
else if (num < 100000000) return 8;
else if (num < 1000000000) return 9;
else if (num < 10000000000ULL) return 10;
else if (num < 100000000000ULL) return 11;
else if (num < 1000000000000ULL) return 12;
else if (num < 10000000000000ULL) return 13;
else if (num < 100000000000000ULL) return 14;
else if (num < 1000000000000000ULL) return 15;
else if (num < 10000000000000000ULL) return 16;
else if (num < 100000000000000000ULL) return 17;
else if (num < 1000000000000000000ULL) return 18;
else if (num < 10000000000000000000ULL) return 19;
else return 20;
}
However when I compile (GCC) I get the following warning:
warning: comparison is always true due to limited range of data type
I understand why I get this repeatedly but I’m not sure how to suppress/avoid it.
Any thoughts?
If you don’t care about user-defined integer types (and evidence suggests that you don’t care about negative values, either), just define one function which takes the largest type that you care about:
If you call it with a
signed shortor whatever, you won’t get any warnings about the implicit conversion, since it’s a widening.static_cast<unsigned>(log10(num)) + 1is also worth profiling.