C objects in a switch statement
I get a compiler error when using an Objective-C object within a switch statement:
switch (myConstant)
{
case 0:
UIViewController *myController = [[[UIViewController alloc] init] autorelease];
[self.navigationController pushViewController:myViewController animated:YES];
break;
case 1:
// stuff
break;
default:
break;
}
The error states:
Expected expression before 'UIViewController'
'myViewController' undeclared (first use in this function)
I understand that the second error is a direct result of the first error, but what I don't understand is why I get the 'expected expression' error in the first place...
If I put a ;
at the end of the case 0:
line, then it will compile, but I shouldn't have to do this, no?
This will also fail to compile, with the same error:
switch (0)
{
case 0:
int a = 0;
break;
default:
break;
}
However, if I declare the int a;
outside of the switch block, then a = 0;
compiles fine.
I thought I understood switch statements - clearly I don't. Could someone please explain?
Just add {} within the case if you declare a new variable. The case part of a switch statement is not a correct scope to declare variables in C.
case 0:
{
int a = 0;
break;
}
...
链接地址: http://www.djcxy.com/p/14768.html
下一篇: 一个switch语句中的C对象