As mentioned in comments, you should be careful about which integer type you use. int
is negative and if your function takes int
as parameter, it will therefore be assumed that it can handle negative numbers. So unsigned int
might have been a better choice.
More importantly, you should be aware that recursion is dangerous, ineffective and often hard to read. The compiler may not always be able to optimize away the recursive call - so-called tail-call optimization - and if it doesn't the function turns very slow and gives a peak in stack memory use.
In this specific case, the compiler should be able to recognize that the else
is redundant and the recursive call ends up at the return statement where it should be in order to enable optimization.
Still, gcc gives me less efficient code for your recursive function than for a loop alternative, even though it could optimize away the recursive call. Disassembling your code and comparing it with this one:
int countDigitsSane (int n){
int digits=1;
for(int i=n; i>9; i/=10)
{
digits++;
}
return digits;
}
Then it gives me slightly worse code for the recursive alternative, https://godbolt.org/z/Ddzv9u. The assembler generated is pretty unreadable with lots of compiler tricks, but writing the code as a plain readable loop is what makes such tricks possible. Usually, code that is easily read by humans is code that is easily optimized by the compiler.
So what was gained from recursion? The code turned slower and harder to read. The uncomfortable truth here is that recursion is mostly used for posing, when the programmer writes needlessly complicated code on purpose to show off.
In the real world where professionals write code with the purpose of making it safe, rugged and maintainable, recursion should be avoided in general. There are very few actual uses for it outside artificial academic exercises - it should pretty much only be used in various specialized search/sort algorithms and never in ordinary application logic. High level language programmers may tell you otherwise, but that's because they don't have a clue about how actual machine code is generated.
countDigits()
with a negative number. Also,unsigned int
may be a more appropriate argument and return type ifcountDigits()
is not intended to count the number of digits of a negative number. It's not difficult to make it work with negative numbers, though... \$\endgroup\$