How does this C code work?
c, pointers, recursion
Solution
Line 2 is checking to see if the current character is the null terminator of the string - since C strings are null-terminated, and the null character is considered a false value, it will begin unrolling the recursion when it hits the end of the string (instead of trying to call StrReverse4 on the character after the null terminator, which would be beyond the bounds of the valid data).
Also note that the pointer is to a `char`, thus incrementing the pointer only increments by 1 byte (since `char` is a single-byte type).
Example:
0 1 2 3
+--+--+--+--+
|f |o |o |\0|
+--+--+--+--+
- When `str` = `0`, then `*str` is `'f'` so the recursive call is made for str+1 = 1.
- When `str` = `1`, then `*str` is `'o'` so the recursive call is made for str+1 = 2.
- When `str` = `2`, then `*str` is `'o'` so the recursive call is made for str+1 = 3.
- When `str` = `3`, then `*str` is `'\0'` and `\0` is a false value thus `if(*str)` evaluates to false, so no recursive call is made, thus going back up the recursion we get...
- Most recent recursion was followed by `putchar('o'), then after that,
- Next most recent recursion was followed by `putchar('o'), then after that,
- Least recent recursion was followed by `putchar('f'), and we're done.
Problem
I was looking at the following code I came across for printing a string in reverse order in C using recursion: ``` void ReversePrint(char *str) { //line 1 if(*str) { //line 2 ReversePrint(str+1); //line 3 putchar(*str); //line 4 } } ``` I am relatively new to C and am confused by line 2. `*str` from my understanding is dereferencing the pointer and should return the value of the string in the current position. But how is this being used as an argument to a conditional statement (which should except a boolean right?)? In line 3, the pointer will always be incremented to the next block (4 bytes since its an int)...so couldn't this code fail if there happens to be data in the next memory block after the end of the string? Update: so there are no boolean types in c correct? A conditional statement evaluates to 'false' if the value is 0, and 'true' otherwise?