Public Group

# 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.

## 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 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 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.

1. 1
2. 2
3. 3
Rutin
20
4. 4
5. 5
khawk
14

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633655
• Total Posts
3013181
×