Jump to content
  • Advertisement
Sign in to follow this  
GameDweeb

Understanding stack logic

This topic is 4784 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!