Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

switch statement in C / Objective C

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;
        }
    }
}
like image 943
Razor Avatar asked Nov 11 '14 15:11

Razor


People also ask

What is switch statement in C with example?

The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.

What is the statement of switch?

In computer programming languages, a switch statement is a type of selection control mechanism used to allow the value of a variable or expression to change the control flow of program execution via search and map.

Is switch-case available in C?

Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory.

What is switch statement and how it works?

The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.


1 Answers

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.

like image 150
ryyker Avatar answered Oct 22 '22 17:10

ryyker