How Recursion works in C -
i new c , i'm reading recursion, totally confused.
the main part i'm getting confused how things unwind when exit condition reached. know how during recursion values got pushed , popped stack.
also can please give me diagramatic view of recursion?
thanks...
lets assume function:
int myfunc(int counter) { // check functions counter value stack (most recent push) // if counter 0, we've reached terminating condition, return if(counter == 0) { return counter; } else { // terminating condition not reached, push (counter-1) onto stack , recurse int valuetoprint = myfunc(counter - 1); // print out value returned recursive call printf("%d", valuetoprint); // return value supplied use // (usually done via register think) return counter; } } int main() { // push 9 onto stack, don't care return value... myfunc(9); } the output is: 0123456789
the first time through myfunc, count 9. fails terminating check (it not 0), recursive call invoked, (counter -1), 8.
this repeats, decrementing value pushed onto stack each time until counter == 0. @ point, terminating clause fires , function returns value of counter (0), in register.
the next call stack, uses returned value print (0), returns value supplied when called (1). repeats:
the next call stack, uses returned value print (1), returns value supplied when called (2). etc, till top..
so, if myfunc invoked 3, you'd equivalent of (ignoring return addresses etc stack):
call myfunc(3) stack: [3] call myfunc(2) stack: [2,3] call myfunc(1) stack: [1,2,3] call myfunc(0) stack: [0,1,2,3] termination fires (top of stack == 0), return top of stack(0). // flow returns to: myfunc(1) stack: [1,2,3] print returned value (0) return current top of stack (1) // flow returns to: myfunc(2) stack: [2,3] print returned value (1) return current top of stack (2) // flow returns to: myfunc(3) stack: [3] print returned value (2) return current top of stack (3) // , you're done...
Comments
Post a Comment