First you need to understand how exactly the recursion is working with the if-statement.
1 2 3 4 5
|
void back(char*k){
if(*k)
back(++k);
printf("%c",*k);
}
|
The recursive case is when the (if statement) evaluates to true:
back(++k);
There's no base case but the recursion is guaranteed to stop when it hits NULL.
We have a pointer to a string, we want to recursively print each character (in reverse) until we reach '\0' which is the end of the string.
if(*k) will evaluate to true when not '\0'
So when the function is called,
The function checks if it has reached the end of the string. If not, then it calls itself with a pointer pointed to the next location of the same string.
(Remember that when the function calls itself, it pauses and starts a new instance of itself. After the instance has finished, it continues.)
This goes on until we reach the '\0'. Now the last instance of the function does not evaluate the if statement, so it goes to the next line without calling itself, which would be the print.
After this instance is done printing, it has done its job, it returns control to the function instance that called it. Now this instance prints the character that it is pointing to and this goes on until all instances have returned.
That is what gives you your output.
Now that you know what makes the recursion work, try to think why using a while-loop in the way you mentioned, wouldn't work. ;)