Home > Enterprise >  C string reversal using recursive function
C string reversal using recursive function

Time:12-03

Hi I came across this piece of code in Youtube when I was searching for a simple string reversal in C. It uses function recursion to print chars from the end to start of the string.

However, I am confused as to how this syntax works when it reaches the null terminator.

#include <stdio.h>

int main() {
    char a[100];
    scanf("%[^\n]s", a);
    reverse(a);
    return 0;
}

void reverse(char* a){
    
    if(*a){
        reverse(a 1);
        printf("%c", *a);
    }
}

Assume that we have the input "HELLO"

What I understand is when recursion is happening, the final if statement continues to the last letter until it stops at the \0 which will make the if statement false, and only then will it start to print the character.

 printf("%c", *a);

which would print the letter "O" just after returns from the call to reverse(\0)

Now, after char 'O' has been printed, it will return again to the function which has *a = L, now.. what I'm understanding is it will keep going back and forth characters O and L.

What am I missing here?

CodePudding user response:

The point here is that you have recursively called the same function multiple times, such that until the moment when the termination character is found none of these function calls have returned.

But once you hit the termination character the stack of function calls "rolls" back so to speak and with every function call returning a character is printed from last to first.

CodePudding user response:

Recursion is very useful thing. I'll try to explain it to you with given example (read left column and follow the arrows)

We're starting with a pointing to H




*a = H         print H and return from recursion
| recursion    ^
v              |
*a = E         print E and return from recursion
| recursion    ^
v              |
*a = L         print L and return from recursion
| recursion    ^
v              |
*a = L         print L and return from recursion
| recursion    ^
v              |
*a = O         print O and return from recursion
| recursion    ^
v              |
*a = '\0'   -> not printing, but returning from recursion

recursion is going to stop here, because *a evaluates to false, so now we're going up with return from recursion (by return I mean end of reverse function)
  • Related