I am new to C and I’m reading about recursion, but I am totally confused.
The main part where I’m getting confused is how things get unwind when the exit condition is reached. I would like to know how during recursion values got pushed and popped from stack.
Also can anyone please give me a diagramatic view of recursion?
Thanks…
Lets assume a function:
The output is: 012345678
The first time through
MyFunc, count is 9. It fails the terminating check (it is not 0), so the recursive call is invoked, with(counter -1), 8.This repeats, decrementing the value pushed onto the stack each time until
counter == 0. At this point, the terminating clause fires and the function simply returns the value of counter (0), usually in a register.The next call up the stack, uses the returned value to print (0), then returns the value that was supplied into it when it was called (1). This repeats:
The next call up the stack, uses the returned value to print (1), then returns the value that was supplied into it when it was called (2). etc, till you get to the top of the stack.
So, if
MyFuncwas invoked with 3, you’d get the equivalent of (ignoring return addresses etc from the stack):