I am trying to understand how putchar('0' + r); works putchar('0' + r); . The function below takes an integer and converts it to binary.
void to_binary(unsigned long n) { int r; r = n % 2; if (n >= 2) to_binary(n / 2); putchar('0' + r); }
I have google putchar definition but I have not found this. To test this, I added printf to see the r value:
void to_binary(unsigned long n) { int r; r = n % 2; if (n >= 2) to_binary(n / 2); printf("r = %d and putchar printed ", r); putchar('0' + r); printf("\n"); }
and I ran it (typed 5) and got this output:
r = 1 and putchar printed 1
r = 0 and putchar printed 0
r = 1 and putchar printed 1
So, I suppose putchar('0' + r); prints 0 if r = 0, else prints 1 if r = 1, or is something else going on?
source share