问题描述
我看到了一些关于这个问题的答案,我明白了——你不能在 switch
中声明和分配变量.但我想知道以下在抛出错误时是否正确
I saw a few answers to this issue, and I get it — you can't declare and assign variables inside a switch
. But I'm wondering if the following is correct at throwing an error saying
错误:'int' 之前的预期表达式
代码:
switch (i) {
case 0:
int j = 1;
break;
}
为什么要在没有错误之前调用 NSLog()
?
Why would putting a call to NSLog()
before it result in no errors?
switch (i) {
case 0:
NSLog(@"wtf");
int j = 1;
break;
}
推荐答案
如果您根据语言的语法进行声明,您实际上可以在开关中声明变量.你会得到一个错误,因为case 0:
"是一个标签,在 C 中将 declaration 作为标签后的第一个语句是非法的——注意编译器需要一个表达式,例如方法调用、正常赋值等.(虽然可能很奇怪,但这是规则.)
You actually can declare variables within a switch if you do it according to the syntax of the language. You're getting an error because "case 0:
" is a label, and in C it's illegal to have a declaration as the first statement after a label — note that the compiler expects an expression, such as a method call, normal assignment, etc. (Bizarre though it may be, that's the rule.)
当您将 NSLog() 放在首位时,您就避免了这个限制.您可以将 case 的内容括在 { } 大括号中以引入作用域块,或者您可以将变量声明移到 switch 之外.您选择哪个是个人喜好的问题.请注意,在 { } 大括号中声明的变量仅在该范围内有效,因此使用它的任何其他代码也必须出现在这些大括号中.
When you put the NSLog() first, you avoided this limitation. You can enclose the contents of a case in { } braces to introduce a scoping block, or you can move the variable declaration outside the switch. Which you choose is a matter of personal preference. Just be aware that a variable declared in { } braces is only valid within that scope, so any other code that uses it must also appear within those braces.
顺便说一下,这种怪癖并不像您想象的那么罕见.在 C 和 Java 中,在 for、while 或 中使用局部变量声明作为单独的语句(意思是没有用大括号括起来)"也是非法的do 循环,甚至在 if 和 else 子句中.(实际上,这在 "Java Puzzlers",我强烈推荐.)我认为我们通常不会写这样的错误开始,因为声明一个变量没有意义作为此类上下文中的唯一语句.但是,对于 switch/case 结构,有些人会省略大括号,因为 break 语句是关键语句用于控制流.
By the way, this quirk isn't as uncommon as you might think. In C and Java, it's also illegal to use a local variable declaration as the lone statement (meaning "not surrounded by braces) in a for, while, or do loop, or even in if and else clauses. (In fact, this is covered in puzzler #55 of "Java Puzzlers", which I highly recommend.) I think we generally don't write such errors to begin with because it makes little sense to declare a variable as the only statement in such contexts. With switch / case constructs, though, some people omit the braces since the break statement is the critical statement for control flow.
要查看编译器是否合适,请将这个可怕的、毫无意义的片段复制到您的 (Objective-)C 代码中:
To see the compiler throw fits, copy this horrific, pointless snippet into your (Objective-)C code:
if (1)
int i;
else
int i;
for (int answer = 1; answer <= 42; answer ++)
int i;
while (1)
int i;
do
int i;
while (1);
总是使用 { } 大括号来分隔此类结构体的另一个原因.:-)
Yet another reason to always use { } braces to delimit the body of such constructs. :-)
这篇关于在 switch 语句中声明变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!