82

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?

Ross
  • 14,266
  • 12
  • 60
  • 91

3 Answers3

169

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.

Community
  • 1
  • 1
Dan Olson
  • 22,849
  • 4
  • 42
  • 56
  • 1
    Interesting. Didn't try the bracket approach. – Eimantas Jan 10 '10 at 11:30
  • Yes this fixes the problem. I was just running with xcode's code fill which doesn't use them. Thanks. – Ross Jan 10 '10 at 11:37
  • 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 Jan 10 '10 at 11:51
  • 25
    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 Jan 10 '10 at 16:15
  • Thanks. This helped me. – Krishna Kanth Yenumula Apr 20 '22 at 18:01
25

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 Declaring variables inside a switch statement for details.

Community
  • 1
  • 1
Quinn Taylor
  • 44,553
  • 16
  • 113
  • 131
3
case 0: {
    Loading my nib file;
    break; 
}
case 1: {
    Loading another nib file;
    break; 
}
Note that if you don't have an assignment (x = y) right after the case it won't be a problem. For example:
kiran kumar
  • 1,349
  • 4
  • 21
  • 40