Switch Statement, varables' value changes
Below is a switch statement, with the conditional varable ,*strItr, being an iterator to a string.
My problem is that when I enter a case, I'm able to create a Node, Node*, and have Node* point to &Node.
I'm able to successfully push the Node* in the nodePtrStack.
The nodePtrStack is declaraed outside of the for loop.
A reference to the element Node* in the stack is visible during debugging.
But when I break from case, the stack resets itself. The element Node* disappears and the stack is now empty, what Im I doing wrong?
I've been searching online but with no success.
thanks for any suggestion.
Code:
for(strItr = userPostfix.begin(); strItr != userPostfix.end(); strItr++)
{
switch(*strItr){
case 'T':
case 't':
{
Node<string>truVar("T", NULL, NULL);
Node<string>* ptruVar = &truVar;
nodePtrStack.push(ptruVar);
break;
}
Re: Switch Statement, varables' value changes
Local variables are stored on the local stack frame.
The object is being lost when scope exits...
Code:
case 'T':
case 't':
{ //-----------------------------------------------start scope
Node<string>truVar("T", NULL, NULL);
Node<string>* ptruVar = &truVar;
nodePtrStack.push(ptruVar);
break;
} //-----------------------------------------------end scope
Move the variable into another area...
Re: Switch Statement, varables' value changes
The stack description makes sense.
But Im not sure what you mean by move the varable?
The nodePtrStack was declared in the beginning of main. So I would assume that the changes to nodePtrStack within the case bracket would be saved.
Re: Switch Statement, varables' value changes
I placed the break statment outside the brackets, while using the debugger, I narrowed down the "wipe out" of varable to occur the moment I exit the curly bracket, but before the break statement.
So now it makes sense that the newly declared and initialized varables are erased when exiting the bracket, so any reference to them will be "wiped out."
But I thought it was ok to use the curly bracket to declare and initialize varables in a switch?
I guess not.
Re: Switch Statement, varables' value changes
Quote:
Originally Posted by
Momentum
But I thought it was ok to use the curly bracket to declare and initialize varables in a switch?
It doesn't matter where the block of code enclosed in { } occurs -- if you declare a variable within that block, it is gone when the block is exited.
Look up variable scope and variable lifetimes.
Regards,
Paul McKenzie
Re: Switch Statement, varables' value changes
And congrats for using a debugger :)