If you know the number is positive, or you want the minus sign to be included in the count:
snprintf(NULL, 0, "%d", a);
If you want the number of digits in the absolute value of the number:
snprintf(NULL, 0, "+%d", a) - 1;
The key to both these solutions is that snprintf
returns the number of bytes it would have written had the buffer been large enough to write into. Since we're not giving it a buffer, it needs to return the number of bytes which it would have written, which is the size of the formatted number.
This may not be the fastest solution, but it does not suffer from inaccuracies in log10
(if you use log10, remember to round rather than truncate to an integer, and beware of large integers which cannot be accurately converted to a double because they would require more than 53 mantissa bits), and it doesn't require writing out a loop.