A switch gotcha

So here's another one for the eagle-eyed among you. This is a little issue I first ran into a little while ago and it was surprising when I discovered the reason behind it.

What's wrong with this code:

switch(controlVariable) {
  case 0:
    NSInteger x = kSomeConstant;
   // some other code...
   break;
  case 1:
   // ...
default:
   // ...
}

At first glance, it looks rather kosher. However, you'd get an error along the lines of:

Unexpected type name 'NSInteger': expected expression

Here's the gotcha gotcha: you must have a statement follow a label and a declaration is not a statement. So, the workaround is to either surround the first case block in curly brackets. e.g.,

case 0:
{
    NSInteger x = kSomeConstant;
   // some other code...
   break;
}

or to put any statement, even if it's an empty one, after the label:

case 0:
  ;
  NSInteger x = kSomeConstant;
  // some other code...
  break;

You can read more about the issue on this StackOverflow thread.

Comments