|
-
November 11th, 2009, 07:45 PM
#1
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;
}
-
November 11th, 2009, 09:24 PM
#2
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...
-
November 11th, 2009, 09:40 PM
#3
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.
-
November 11th, 2009, 10:12 PM
#4
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.
-
November 11th, 2009, 10:24 PM
#5
Re: Switch Statement, varables' value changes
 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
-
November 11th, 2009, 10:40 PM
#6
Re: Switch Statement, varables' value changes
And congrats for using a debugger
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|