Reputation: 435
I am solving the TowerOfHanoi problem, using stacks in STL (C++). But I am not sure why I am getting this warning at line 6703:
When I get this warning, I don't get the intended result on running the program. The program shows no output on the console window and the console window simply says - "Press any key to continue..."
But, when I put a return statement in front of line 6703, the warning goes away and, I get the correct result on the output console window:
And, following is the output on the console, when I append return
in front of the function call (at line 6703) -
Why do I have to append return
in front of the function call, for it to work correctly?
If we look at the call stack, there are three call stacks created:
1. One for main
2. The second for towerOfHanoi(stack1,stack2,stack3, 3)
3. The third for towerOfHanoi(stack1,stack2,stack3, 2)
After that, stack unwinding process begins -
3. towerOfHanoi(stack1,stack2,stack3, 2)
returns stack3 to towerOfHanoi(stack1,stack2,stack3, 3)
2. Now, towerOfHanoi(stack1,stack2,stack3, 3)
in turn returns stack3 to main()
Am I correct on how the stack unwinding process is going on? And, return is essential at line 6703: return towerOfHanoi(stack1, stack2, stack3, n - 1)
- because if it is absent, we will fail to return the stack3 to main
? -
Can you please explain me the stack frame unwinding process better?
Upvotes: 0
Views: 213
Reputation: 588
towerOfHanoi(stack1,stack2,stack3, 2) returns stack3 to towerOfHanoi(stack1,stack2,stack3, 3) beacuse of
if (n == 2) {
return stack3;
}
but
towerOfHanoi(stack1,stack2,stack3, 3) doesnt return anything to main. Because you didnt provided a return statement at the end function.
Upvotes: 2