[Solved] what is the order of execution if I put a statement after the statement that do the recursion inside the function


okay it’s really simple.

Just consider these two points before moving on:

point 1:
When a function calls another function, the first function that calls the other is known as the “caller” function, the function getting called is known as the “callee”.

point 2: when a callee is called, code execution stops at the point where the call was made and moves inside the callee and runs all the way through the callee, until it either finishes all the lines or reaches a return statement for a non void function or reaches another function call.

so here in your program:
main () calls print (x).
main() stops executing where print(x); was written

assuming x = 5, 5 is passed to void print (int x).

so now inside void. x is 5.

the if (5==0) statement is checked and evaluates to false, so else{} gets executed.

here is the part that confuses you:

inside else{}, there is a function call print (x-1);
this will call the function print (int x) recursively. passing it the value of 5-1=4.
so at this point, the function doesn’t continue to the next line to execute cout << x << endl; instead it pauses inside this function and moves into another function.

notice how print (x-1) is called before cout<< x << endl; is even reached.

so print (x-1) runs, checking the if statement, and calling another print (x-1).
this continues, until x==0, which has a return with no return values which only terminates the function.

so the last function call (x==0) is terminated by the return; statement.

the function before it, which had the value of 1 (remember now x=1), continues from where it paused which was where print (x-1) was stated, and executes the code to the end of the function, so it executes cout<< x << endl; with x = 1.

then when this function is done, the function before it continues its execution in the same way , so first 1 was printed, now 2 gets printed, then 3, 4 and 5… until the whole cycle of functions waiting in line for their callee to finish executing ends..

recursive functions always get to the last call, and start evaluating and finalizing from the last one to the first one because a function call stops the caller from continuing to execute its code and instead makes the program execute inside the callee.

0

solved what is the order of execution if I put a statement after the statement that do the recursion inside the function