views:

2605

answers:

3

Hello,

Cut to the chase I have recreated my problem as it is fairly self explanatory.

this complies without error:

switch (n) {
    case 1:
        NSLog(@"");
        NSString *aStr;
        break;
    default:
        break;
    }

this compiles with error and it's only missing the NSLog():

switch (n) {
    case 1:
        NSString *aStr;
        break;
    default:
        break;
    }

it throws an error at compile "Expected expression before 'NSString'"

Am I missing something here?

+16  A: 

In normal C you'd have to enclose this in brackets in both cases. I suspect this may fix your problem:

case 1:
{
    NSLog(@"");
    NSString *aStr;
    break;
}

See this SO question for more info.

Another way to get around this problem is to put a statement between the case label and the first declaration as you've done in your working example above. See the comments and Quinn Taylor's answer for more info.

Dan Olson
Interesting. Didn't try the bracket approach.
Eimantas
Yes this fixes the problem. I was just running with xcode's code fill which doesn't use them. Thanks.
Ross
I've come across this problem before, I solved it using { } myself, good to see it was the correct solution. +1 for you Dan.
David Wong
You don't necessarily have to use brackets. Putting an empty statement (`;`) after the `case` label works, too. The reason for the error and the reason why both solutions work is that a label, including a `case` label, can only precede a statement. Declarations aren't statements in C (C99 §6.7, §6.8, §6.8.2) and Objective-C, so you can't put a label immediately before a declaration. Thus the solutions: Either put a statement (such as `;` or `NSLog(@"");`) between the label and declaration, or wrap the declaration inside a compound statement (the brackets) following the label.
Peter Hosey
A: 

You can't create objects in switch statement. I have tripped over this before. Did a "WTF?", created object outside the switch statement and moved on.

Although I AM interested why it's the way it is.

Eimantas
http://stackoverflow.com/questions/92396/why-cant-variables-be-declared-in-a-switch-statement
Dan Olson
edit- answer to below, above, after page refresh:Now we can now with @Dan Olson answer, but it would be good to know it it's not good practise?...
Ross
+1. Thanks Dan!
Eimantas
“You can't create objects in `switch` statement.” Yes you can. You just can't put a label (including a `case` label) before a declaration.
Peter Hosey
For a thorough explanation, see http://stackoverflow.com/questions/1180550/weird-switch-error-in-obj-c/1181106#1181106%3E
johne
+2  A: 

You can't declare a variable as the first statement in a case without brackets, and in many other contexts in C-based languages. See http://stackoverflow.com/questions/1231198/ for details.

Quinn Taylor