objective-c 编译错误:开关,“之前的预期表达式”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2036819/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Compile Error with: switch, "expected expression before"
提问by Ross
Cut to the chase I have recreated my problem as it is fairly self explanatory.
切入正题 我重新创建了我的问题,因为它是不言自明的。
this complies without error:
这符合没有错误:
switch (n) {
case 1:
NSLog(@"");
NSString *aStr;
break;
default:
break;
}
this compiles with errorand it's only missing the NSLog():
这编译有错误,它只缺少 NSLog():
switch (n) {
case 1:
NSString *aStr;
break;
default:
break;
}
it throws an error at compile "Expected expression before 'NSString'"
它在编译时抛出错误“ 'NSString'之前的预期表达式”
Am I missing something here?
我在这里错过了什么吗?
回答by Dan Olson
In normal C you'd have to enclose this in brackets in both cases. I suspect this may fix your problem:
在普通 C 中,您必须在两种情况下将其括在括号中。我怀疑这可能会解决您的问题:
case 1:
{
NSLog(@"");
NSString *aStr;
break;
}
See this SO questionfor more info.
有关更多信息,请参阅此 SO 问题。
Another way to get around this problem is to put a statement between the case label and the first declaration as you've done in your working example above. See the comments and Quinn Taylor's answer for more info.
解决此问题的另一种方法是在 case 标签和第一个声明之间放置一个语句,就像您在上面的工作示例中所做的那样。有关更多信息,请参阅评论和 Quinn Taylor 的回答。
回答by Quinn Taylor
You can't declare a variable as the firststatement in a casewithout brackets, and in many other contexts in C-based languages. See Declaring variables inside a switch statementfor details.
您不能在没有括号的a 中以及在基于 C 的语言的许多其他上下文中将变量声明为第一条语句case。有关详细信息,请参阅在 switch 语句中声明变量。
回答by kiran kumar
case 0: {
Loading my nib file;
break;
}
case 1: {
Loading another nib file;
break;
}
Note that if you don't have an assignment (x = y) right after the case it won't be a problem. For example:

