开发者

Odd compiler error when using Obj-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;
    }
...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜