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;
}
}
}
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.
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.
Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With