Sign in to follow this  
GameDweeb

Understanding stack logic

Recommended Posts

I've got a progam that looks like this: int hanoi(int n, int src, int aux, int dst) { if (n == 0) { return 0; } hanoi(n-1, src, dst, aux); cout << n << " " << src << " -> " << dst << endl; hanoi(n-1, aux, src, dst); return 1; } I can't seem to get a handle on how the logic works, I've got a basic understanding of how recursion works. I just can't figure out how to follow the variables that are being passed around from call to call. Can anyone help?

Share this post


Link to post
Share on other sites
Use step through on your debugger while watching the output?
It does look quite interesting:
I guess the first call to the function is:
hanoi(n, peg1, peg2, peg3)
where n is the number of pieces in the puzzle, peg1 is the peg all the pieces start on, peg2 is the empty peg, and peg3 is the peg you want them all to end up on.
I would guess if you search for a description of how to do the towers of hanoi, it would shed some light.

Share this post


Link to post
Share on other sites
Here's a general explanation. Every function call pushes the arguments onto the stack. As the recursion proceeds, the arguments pile up on the stack like an array. When the recursion termination condition is reached, unwinding begins. The arguments now on the stack are operated on and popped from the stack. When unwinding completes the final result is returned.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this