Declaring variables inside a switch statement [duplicate]
Solution 1:
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. :-)
Solution 2:
I've run into this issue before, and the conclusion was that you just put the code inside a block.
switch (i) {
case 0:
{
int j = 1;
break;
}
}
Solution 3:
Another simple workaround I use is to add an empty expression (semicolon) before the declaration. This avoids limiting the variable scope to a code block (or having some case statements with code blocks and some without).
switch (i) {
case 0:;
int j = 1;
break;
}