Learn Objective-C: The switch Statement

The switch() statement is used in place of a chain of if()…else if()…else if()…else if()…else construct, where such a chain does not lead to very readable, follow-able code. The switch() statement is designed for this situation. Here is the general format:

switch(expression or variable) {
     case value1:
          // Program statement
          // Program statement
          ...
          break;
     case value2:
          // Program statement
          // Program statement
          ...
          break;
     case value3:
          // Program statement
          // Program statement
          ...
          break;
     ...
     case valueN:
          // Program statement
          // Program statement
          ...
          break;
     default:
          // Program statement
          // Program statement
          ...
          break;
}

The expression value in the parentheses at the beginning of the statement is compared to each of the values, and when one of them matches, the following code (note the colon, and the lack of braces around each case), the code below is executed. It then breaks out of the rest of the switch, to avoid executing the rest of it (“overflowing” into the code for the next condition). This can sometimes be used intentionally, but for most of the time make sure to use the break; statement.

If none of the conditions match (the else of an if()…else block), the code under the default condition is executed.

The following is an example of a switch() statement and the equivalent if()…else block:

// This is an example of a switch statement.
#import <Foundation/Foundation.h>

int main (int argc, const char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *operator = [[NSString alloc] init];     // We will talk in depth about NSString later on down the road.
    // Assume operator has been initialized to a valid value
    // Valid values for operator are @"+", @"-", @"*", and @"/"

    switch (operator) {
        case @"+":
            NSLog(@"Operator is for addition.");
            break;
        case @"-":
            NSLog(@"Operator is for subtraction.");
            break;
        case @"*":
            NSLog(@"Operator is for multiplication.");
            break;
        case @"/":
            NSLog(@"Operator is for division.");
            break;
        default:
            NSLog(@"Unknown operator.");
            break;
    }

    [pool drain];
    return 0;
}

This code should be rather self-explanatory; operator is compared to the values after each case, and if one of them matches, the executes the corresponding NSLog and breaks out of the switch. If none of them match, then it hits the default statement.

The equivalent if()…else block follows:

// This is an example of a switch statement.
#import <Foundation/Foundation.h>

int main (int argc, const char *argv[]) {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSString *operator = [[NSString alloc] init];
    // Assume operator has been initialized to a valid value
    // Valid values for operator are @"+", @"-", @"*", and @"/"

    /* Note that NSString actually has a comparison method, and that
       this method of comparison is not guaranteed to work. We are
       overlooking that at the moment for the sake of education. */
    if (operator == @"+")
        NSLog(@"Operator is for addition.");
    else if (operator == @"-")
        NSLog(@"Operator is for subtraction.");
    else if (operator == @"*")
        NSLog(@"Operator is for multiplication.");
    else if (operator == @"/")
        NSLog(@"Operator is for division.");
    else
        NSLog(@"Unknown operator.");
    
    [pool drain];
    return 0;
}

This code does the same thing as the switch statement above (bar the multi-line comment).

The switch() statement is makes more logical sense, but some people find it annoying. It all comes down to a matter of personal preference. No big deal.

Postscript: Wikipedia has a nice article on controlling program flow. And while you’re there, you might as well see the article on the switch statement as well.

This post is part of the Learn Objective-C in 24 Days course.