I am looking at the following piece of code:
void printd(int n)
{
if (n < 0) {
putchar('-');
n = -n;
}
if (n / 10)
printd(n / 10);
putchar(n % 10 + '0');
}
I understand the first if statement fine, but the second one has me confused on a couple of points.
By itself, since “n” is an integer, I understand that n/10 will shift the decimal point to the left once – effectively removing the last digit of the number; however, I am having a little trouble understanding how this can be a condition by itself without the result being equal to something. Why isn’t the condition if ((n/10) >= 0) or something?
Also, why is the ‘0’ passed into the putchar() call?
Can someone tell me how it would read if you were to read it aloud in English?
Thanks!
The
n / 10will evaluate to false if the result is 0, true otherwise. Essentially it’s checking ifn > 10 && n < -10(the -10 doesn’t come into play here due to then = -ncode)The
+ '0'is for character offset, as characters ‘0’-‘9’ are not represented by numbers 0-9, but rather at an offset (48-57 with ascii).If you’re talking about the conditional, then I would say “if integer n divided by 10 is not zero”