Objective-C Tip: Switch Statements

During one of my sessions of working on the iPhone game. I noticed something very strange within Objective-C.

Apparently, this will get a compiler error as it expects an expression to be place before the declaration. I did a little searching around and was unable to find much on why this causes an error. I did however, find a few solutions that seem to work really well.

Considering the error is that the compiler expected an expression before the declaration you can try to rearrange your statements so that declarations are not the first statements within the case statement.

…or you can just place an empty semicolon if the above example is not an option.

Last, I found a better solution to the above examples and it is the one I’ll be using. I really don’t know exactly why this one works as it is not really an expression but by adding { and } to separate the block of code within the case statement. We are allowed to place our variable declarations at the top.

I like this solution the best cause it continues to give me the freedom on where I want to place my statements and expressions and, as a double whammy, helps in readability since the block of code will now be indented one block.

Author: Scyanide

Software Engineer wanting to share his experiences.

2 thoughts on “Objective-C Tip: Switch Statements”

  1. Hmm…
    Does Objective-C have closures then? What else could the braces be representing…?
    It would be interesting to look at what the code compiles to — it may reveal the answer.

    1. Obj-C does have closures and in fact they use the curly braces quite often for statements. I will admit that it took me a bit to understand that header files are treated a bit differently from traditional C.

      @interface GameBoard : CCNode
      {
      @private
      GamePiece *gameBoard[BOARD_HEIGHT][BOARD_WIDTH];
      }

      -(void)selectGamePiece:(CGPoint)touchedPoint;

      @end

      ..this is a piece taken from my GameBoard class. From what I’ve gathered, everything within the @interface and @end is the class declarations. However, everything within the curly braces are class variable declarations. Interesting form of grouping but I do like it.

Leave a Reply