Backwards

This program outputs the input written backwards, but I don't get how it works when looking at the code. Could someone explain it to me?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

void baklanges(){
     char c;
     if(cin.get(c)){
        baklanges();
        cout << c;
     }
}

int main(){
    baklanges();
}
It is a recursive function. The first character entered is printed last. So you have a stack model.
To expand on vlad's answer (because I started typing it ages ago and didn't finish ;) ):

It's recursive - i.e. baklanges calls itself.

It only outputs a letter after the recursive call returns - i.e. after recursion ends.

The first time cout << c executes will be within the deepest recursive call - i.e. it will be the last letter entered.

The next time it executes will be in the second deepest recursion, i.e. the second last character entered.

And so on...
Topic archived. No new replies allowed.