switch statement in C / Objective C

瘦欲@ 提交于 2019-12-21 07:18:10

问题


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

回答1:


You can think of the switch(value){case label:, ...} construct as a variable goto <label> statement, where:

1) switch(arg) determines which label execution will flow to next.
2) The key word case : defines the label. Example: case label:.

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).

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.

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.



来源:https://stackoverflow.com/questions/26868663/switch-statement-in-c-objective-c

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