A switch statement gotcha in Objective-C
If you let XCode's code completion create your switch statement for you, you might run into this little gotcha.
The following code...
NSUInteger i;
switch (i) {
case 0:
// Do something
break;
default:
NSString *s = @"something";
s;
break;
}
... doesn't compile. Instead, you get the following two errors:
- Expected expression before 'NSString'
- 's' undeclared (first use in this function)
The culprit is the auto-generated code. The following code does compile. Note the curly braces.
NSUInteger i;
switch (i) {
case 0:
{
// Do something
break;
}
default:
{
NSString *s = @"something";
s;
break;
}
}
The curly brackets are not required for switch statements but when they are absent, a statement must follow the case
or default
labels. Declarations are not statements in C and thus result in this error.
The following code, which doesn't use curly braces, also compiles.
NSUInteger i;
switch (i) {
case 0:
// Do something
break;
default:
NSLog(@"Magic? Not really, just a statement.");
NSString *s = @"something";
s;
break;
}
Hope this helps you in case you encounter this sneaky little gotcha!
Interested in learning iPhone development? Check out my Introduction to iPhone App Development Course.
Comments
by Zhami on 2010-02-02 00:30:36
by Jamie Lmon on 2010-04-26 14:39:01
by Magnus Ahlberg on 2010-04-15 21:50:23
by Derek on 2010-05-23 04:19:00
by John Tabernik on 2010-11-29 02:29:56
by people_at_work on 2011-01-07 22:02:17
by Mark on 2011-06-02 18:43:38