Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a block in a switch statement results in a compiler error

Tags:

objective-c

Consider the following switch statement:

switch (buttonIndex) {     case 0:         [self fooWithCompletion:^{             [weakSelf finishEditing];         }];         break;     case 1: // Error here         [self barWithCompletion:^{             [weakSelf finishEditing];         }];         break;         default:         break; } 

It causes the compiler error

Cannot jump from switch statement to this case label

on the line case 1:.

Why is this happening and how do I fix it?

like image 327
aednichols Avatar asked Nov 05 '15 17:11

aednichols


People also ask

Which variable is not allowed in switch statement?

The switch statement doesn't accept arguments of type long, float, double,boolean or any object besides String.

Can we use variables in switch case in C?

Do not declare variables inside a switch statement before the first case label. According to the C Standard, 6.8.

Why are variables not allowed to be used as the case values in a switch?

If the cases were allowed to contain variables, the compiler would have to emit code that first evaluates these expressions and then compares the switch value against more than one other value. If that was the case, a switch statement would be just a syntactically-sugarized version of a chain of if and else if .

Can we use variables in switch case?

Variables are not allowed. The default statement is optional and can appear anywhere inside the switch block. In case, if it is not at the end, then a break statement must be kept after the default statement to omit the execution of the next case statement.


1 Answers

The block definition creates a new scope which seems to interfere with the compiler's ability to correctly interpret the switch statement.

Adding scope delimiters for each case label resolves the error. I think this is because the block's scope is now unambiguously a child of the case scope.

switch (buttonIndex) {     case 0:     {         [self updateUserDataWithCompletion:^{             [weakSelf finishEditing];         }];         break;     }     case 1:     {         [self updateOtherDataWithCompletion:^{             [weakSelf finishEditing];         }];         break;     }     default:         break; } 

There's a bug open with LLVM for a similar issue.

like image 196
aednichols Avatar answered Nov 05 '22 16:11

aednichols