I'm learning the concept of recursion and, to pratice my knowledge, I wrote the following program.
#include <bits/stdc++.h>
using namespace std;
int c = 0;
int add(int a) {
if (a == 0) {
return c;
}
c = c + 1;
add(a - 1);
cout << "Hello";
}
int main() {
int x = add(6);
cout << "Final " << x;
}
It produces this output, which is not what I expected:
HelloHelloHelloHelloHelloHelloFinal 5134464
Why the program is not terminating when the a==0
condition is satisfied and it returns the final result to the main function?
Instead of that, it's printing "Hello"
6 times, but the output statement is after the recursion call.
Why code after the recursion call is still executed multiple times?
I expected it would never be executed.
I'm still trying to understand how recursion works, so I'd like to know what exactly is happening here.