Odd compiler error when using Obj-C objects in a switch statement

自古美人都是妖i 提交于 2020-02-24 06:01:25

问题


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?


回答1:


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;
    }
...


来源:https://stackoverflow.com/questions/4068909/odd-compiler-error-when-using-obj-c-objects-in-a-switch-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!