C/Objective C 中的 switch 语句 [英] switch statement in C / Objective C
问题描述
我是Objective-C的新手,但从我对switch语句的了解来看,下面的代码不应该打印任何东西,因为在我看来应该是编译错误.但是 2 被打印出来.我不明白为什么.有人可以解释一下吗?
I am new to Objective-C, But from all I know about switch statements, the following code should not print anything, because to me it seems that there should be a compilation error. However 2 is printed. I do not understand why. Could someone please explain?
- (void) test {
int myVar = 2;
switch (myVar) {
case 1:
{
NSLog(@"result: %d", myVar);
break;
case 2:
{
NSLog(@"result: %d", myVar);
}
break;
}
}
}
推荐答案
您可以将 switch(value){case label:, ...}
结构视为 变量 goto
语句,其中:
You can think of the switch(value){case label:, ...}
construct as a variable goto <label>
statement, where:
1) switch(arg)
决定接下来执行哪个 label
.
2) 关键字case : 定义了标签强>.示例:案例标签:
.
1) switch(arg)
determines which label
execution will flow to next.
2) The key word case : defines the label. Example: case label:
.
在 switch 语句中,case
关键字后跟一个标签(常量表达式后跟一个 :
),就像 中使用的标签一样>goto
语句.控制传递给语句 case constant-expression
与语句 switch(arg)
中 arg 的值匹配的语句.
In a switch statement, the case
key word is followed by a label (constant expression followed by a :
), which is treated like the label used in goto
statements. Control passes to the statement whose case constant-expression
matches the value of arg in the statement switch(arg)
.
因此从法律上讲,您的代码没有语法错误.也就是说,它将编译和构建,并且运行得很好.您的示例代码中的语法唯一违反的是可读性,因为执行流程忽略了块 {...}
,在大多数情况下,它会直接执行流程,并且直接跳转到由 case
关键字定义的目标标签,就像它应该的那样.
So legally there is nothing syntactically wrong with your code. That is, it will compile and build, and run just fine. The only thing the syntax in your example code violates is readability in that the execution flow ignores the block {...}
, which in most cases would direct execution flow, and jumps directly to the targeted label defined by the case
key word, just as it should.
忽略成熟的先例来试验新的混合结构通常不会产生有用的结果.但当它发生时,结果可以成为传奇.例如,查看 Duff 的设备强>.
It's not often that ignoring well established precedent to experiment with new hybrid constructs will yield useful results. But when it does, the results can become legendary. For example, see Duff's Device.
这篇关于C/Objective C 中的 switch 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!