I am currently learning how recursion work by reversing a sentence and I can’t seem to understand how the char variable is able to store a string without using square brackets or curly braces and how it iterates to the next character
I am new to this and I hope my question isn’t too simple to ask
#include <stdio.h>
void swap_recursion();
int main() {
printf("Input a sentence: ");
swap_recursion();
return 0;
}
void swap_recursion(){
char sentence;
scanf("%c", &sentence);
if (sentence != '\n'){
swap_recursion();
printf("%c", sentence);
}
}
>Solution :
The string is stored in multiple instances of char sentence; on the stack. Each recursive call of swap_recursion() makes a new char sentence; on the stack, and stores one character from the input there. The stack keeps building up until a new line is encountered. At that point, the entire string is stored on the stack. Then each character is printed in the reverse order they were read, by unrolling the stack with each return.