Recursion problem, C language

1

I have a problem, in a code that I found in that it receives a user string and returns it inverted, doing so in a recursive way.

However, I do not understand why the function actually does this.

Follow the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void recebeString(char *string)
{
    if(*string)
    {
        recebeString(string+1);
        putchar(*string);

    }

}

int main()
{
    char resultado[250];

    printf("Escreva uma string(frase): ");
    scanf("%[^\n]",resultado); // força o scanf a ler ate encontrar o \n.
    setbuf(stdin, NULL);

    printf("%s\n\n",resultado);

    recebeString(resultado);


    return 0;

}

Can anyone help me?

    
asked by anonymous 01.03.2018 / 20:38

1 answer

2

What the function does is to call itself by incrementing the pointer of the string, so the calls are stacked in memory, until there will come a time when if will fail because it will find putchar ending the string (assuming the string is well formed). Then it will return to the last call at the point just before putchar and will execute the putchar of the last character. And it will keep popping up and calling %code% .

That's why it works.

    
01.03.2018 / 20:42