Declaring variables inside a switch statement

dizy picture dizy · Aug 5, 2009 · Viewed 30.1k times · Source

I saw a few answers to this issue, and I get it — you can't declare and assign variables inside a switch. But I'm wondering if the following is correct at throwing an error saying

error: expected expression before 'int'

Code:

switch (i) {
    case 0:
        int j = 1;
        break;
}

Why would putting a call to NSLog() before it result in no errors?

switch (i) {
    case 0:
        NSLog(@"wtf");
        int j = 1;
        break;
}

Answer

Quinn Taylor picture Quinn Taylor · Aug 5, 2009

You actually can declare variables within a switch if you do it according to the syntax of the language. You're getting an error because "case 0:" is a label, and in C it's illegal to have a declaration as the first statement after a label — note that the compiler expects an expression, such as a method call, normal assignment, etc. (Bizarre though it may be, that's the rule.)

When you put the NSLog() first, you avoided this limitation. You can enclose the contents of a case in { } braces to introduce a scoping block, or you can move the variable declaration outside the switch. Which you choose is a matter of personal preference. Just be aware that a variable declared in { } braces is only valid within that scope, so any other code that uses it must also appear within those braces.


Edit:

By the way, this quirk isn't as uncommon as you might think. In C and Java, it's also illegal to use a local variable declaration as the lone statement (meaning "not surrounded by braces) in a for, while, or do loop, or even in if and else clauses. (In fact, this is covered in puzzler #55 of "Java Puzzlers", which I highly recommend.) I think we generally don't write such errors to begin with because it makes little sense to declare a variable as the only statement in such contexts. With switch / case constructs, though, some people omit the braces since the break statement is the critical statement for control flow.

To see the compiler throw fits, copy this horrific, pointless snippet into your (Objective-)C code:

if (1)
    int i;
else
    int i;
for (int answer = 1; answer <= 42; answer ++)
    int i;
while (1)
    int i;
do
    int i;
while (1);

Yet another reason to always use { } braces to delimit the body of such constructs. :-)