The Objective-C switch Statement

Follow Techotopia on Twitter Bookmark and Share

From Techotopia

Jump to: navigation, search
PreviousTable of ContentsNext
Objective-C Flow Control with if and elseObjective-C Looping - The for Statement

Purchase the full edition of this Objective-C book in Print ($14.99) or eBook ($12.99) format
Objective-C 2.0 Essentials Print and eBook (ePub/PDF/Kindle) editions contain 31 chapters.

Buy eBook
Buy Print


In Objective-C Flow Control with if and else we looked at how to control program execution flow using the if and else statements. Whilst these statement constructs work well for testing a limited number of conditions they quickly become unwieldy when dealing with larger numbers of possible conditions. To simplify such situations Objective-C has inherited the switch statement from the C programming language. In this chapter we will explore the switch statement in detail.

Contents




[edit] Why Use a switch Statement?

For a small number of logical evaluations of a value the if ... else if ... construct outlined in Objective-C Flow Control with if and else is perfectly adequate. Unfortunately, any more than two or three possible scenarios can quickly make such a construct both time consuming to write and difficult to read. As a case in point consider the following code example. The program is designed to evaluate integers between 0 and 5 entered at the keyboard and to output the word version of the number (zero, one, two etc):

#import <Foundation/Foundation.h>

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

      int value;

      printf ("Enter a number between 0 and 5: ");

      scanf ("%i", &value);

      if (value == 0)
        NSLog (@"zero");
      else if (value == 1)
        NSLog (@"one");
      else if (value == 2)
        NSLog (@"two");
      else if (value == 3)
        NSLog (@"three");
      else if (value == 4)
        NSLog (@"four");
      else if (value == 5)
        NSLog (@"five");
      else
        NSLog (@"Integer out of range");

      [pool drain];
      return 0;
}

As you can see, whilst the code is not too excessive it is already starting to become somewhat hard to read and also took more time to write than should really be necessary. Imagine, however, if instead of five numbers we had to test for more. Clearly an easier solution is needed, and that solution is the switch statement.

[edit] Using the switch Statement Syntax

The syntax for an Objective-C switch statement is as follows:

 switch (expression)
{ case match1:
statements
break;
case match2:
statements
break;
default:
statements
break;
}

This syntax needs a little explanation before we embark on creating a switch based version of the above if ... else construct.

In the above syntax outline expression represents either a value, or an expression which returns a value. This is the value against which the switch operates. Using our example, this would be the integer to be evaluated.

For each possible match a case statement is required, followed by a match value. Each potential match must be of the same type as the governing expression. Following on from the case line are the Objective-C statements that are to be executed in the event of the value matching the case match.

After the statements comes a break statement. This statement breaks out of the switch statement. Failure to provide a break statement results in every case after the matching case evaluating to true (regardless of whether the match is made or not) and the corresponding Objective-C statements executing.

Finally, the default section of the construct defines what should happen if none of the case statements present a match to the expression.

[edit] A switch Statement Example

With the above information in mind we may now construct a switch statement which provides the same functionality as our previous and somewhat unwieldy if ... else if ... construct:

#import <Foundation/Foundation.h>

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

   int value;

   printf ("Enter a number between 0 and 5: ");

   scanf ("%i", &value);

   switch (value)
   {
      case 0:
        NSLog (@"zero");
        break;
      case 1:
        NSLog (@"one");
        break;
      case 2:
        NSLog (@"two");
        break;
      case 3:
        NSLog (@"three");
        break;
      case 4:
        NSLog (@"four");
        break;
      case 5:
        NSLog (@"five");
        break;
      default:
        NSLog (@"Integer out of range");
        break;
   }
        [pool drain];
        return 0;
}

[edit] Explaining the Example

When compiled and run, the sample application will prompt for a number between 0 and 5. Once entered, the response is assigned to the integer variable value which in turn is used as the governing variable in the switch statement.

The default option simply displays an out of range message if none of the case statements match the number entered by the user.

[edit] Combining case Statements

In the above example, each case had its own set of statements to execute. Sometimes a number of different matches may require the same code to be executed. In this case, it is possible to group case statements together with a common set of statements to be executed when a match for any of the cases is found. For example, we can modify the switch construct in our example so that the same code is executed regardless of whether the user enters 0, 1 or 2:

   switch (value)
   {
      case 0:
      case 1:
      case 2:
        NSLog (@"zero, one or two");
        break;
      case 3:
        NSLog (@"three");
        break;
      case 4:
        NSLog (@"four");
        break;
      case 5:
        NSLog (@"five");
        break;
      default:
        NSLog (@"Integer out of range");
        break;
   }
Purchase the full edition of this Objective-C book in Print ($14.99) or eBook ($12.99) format
Objective-C 2.0 Essentials Print and eBook (ePub/PDF/Kindle) editions contain 31 chapters.

Buy eBook
Buy Print



PreviousTable of ContentsNext
Objective-C Flow Control with if and elseObjective-C Looping - The for Statement
Views
Personal tools

Find us on Facebook