Re: why can't you initialize variable in case statements
Re: why can't you initialize variable in case statements
- Subject: Re: why can't you initialize variable in case statements
- From: Scott Fraser <email@hidden>
- Date: Wed, 21 Sep 2005 15:29:43 -0700
On Sep 21, 2005, at 02:24 PM, email@hidden wrote:
Hello,
In trying to port to xcode, I get errors when a variable is
initialized after any goto statement or within a case statement.
Why? Is that a problem?
error: jump to case label
error: crosses initialization of 'int handled'
Thanks
Bob
You can, sometimes, initialize variables in switch statements. It
depends. Simple variables can (or could) be initialized, if they don't
have C++ constructors. Variables might be initialized in the last
"case" of the switch. The key is to look at the scope of the variable.
The scope of a variable starts at the point in the file where it is
defined, and extends to the end of the block. With a switch statement,
the end of the block is (usually) the curly brace at the end of the
statement. When execution leaves the switch block, C++ destructors are
called for variables going out of scope. However, if your switch
statement never executed the C++ constructor for the variable (eg
because execution jumped over the definition to the last "case") you've
got a serious problem.
(this pseudo code is from memory and is not guaranteed to compile)
switch (someKey)
{
case 1:
someClassPointer myClassPointer = new
someClassPointer(anInitialValue);
myClassPointer->doesSomething();
break;
case 2:
someOtherClass myOtherPointer = new someOtherClass(anInitialValue);
myOtherPointer->doesSomethingElse();
break;
}
When "someKey" is "2", the constructor for "myClassPointer" is never
called, but the destructor is called at the end of the statement.
Similarly, when "someKey" is "1", the constructor for "myOtherPointer"
is never called, but the destructor would be.
The workaround is to add a separate block to contain each "case" which
contains an initialized variable.
switch (someKey)
{
case 1:
{
someClassPointer myClassPointer = new
someClassPointer(anInitialValue);
myClassPointer->doesSomething();
break;
}
case 2:
{
someOtherClass myOtherPointer = new someOtherClass(anInitialValue);
myOtherPointer->doesSomethingElse();
break;
}
}
Now, each class instance goes out of scope (and its destructor is
called) as it leaves the "case", rather than the "switch".
If your code requires a variable be initialized in one "case", and then
referenced in a separate "case" (or especially a fall through "case"),
you need to refactor your code to put the definition before the switch.
Scott
-----
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Xcode-users mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden