Recursive function

Can someone please explain to me step by step why is this code showing 32*23?
I tried to understand it using the debugger in VS, but I just can't understand from where it got the last 2 numbers(23).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 void f(int a) {
   if (a <= 1){
    cout << "*"; 
   }
   else {
    cout << a;
    f(a - 1);
    cout << a;
   }
}
int main()
 {
 f(3);
 }
Compare
1
2
3
    cout << a;
    f(a - 1);
    cout << a;

with
1
2
3
    cout << 'X';
    f(a - 1);
    cout << a;

with
1
2
3
    cout << a;
    f(a - 1);
    cout << 'Y';


It's also helpful to study f(1) and f(2) before trying to single-step f(3).
Every recursive call "pushes" a stack frame. When the calls return, the stack frames are "popped" in reverse order.

f(3); // a = 3
{
    cout << a;              // 3
    f(a - 1); // a = 2
    {
        cout << a;          // 2
        f(a - 1); // a = 1
        {
            cout << '*';    // *
        }
        cout << a;          // 2
    }
    cout << a;              // 3
}

Also, think about how this program works:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

void reverse(const char* s)
{
    if (*s != '\0')
    {
        reverse(s + 1);
        std::cout << *s;
    }
}

int main()
{
    reverse("abcde");  // prints: edcba
    std::cout << '\n';
}

Last edited on
salem, dutch, you are awesome!
Thank you for your explanations. It is crystal clear to me now:)
Topic archived. No new replies allowed.