Extension 5: 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 comment in bold).

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.

BTW less than a month after the previous milestone we are at 2000 views! Thanks to everyone who stopped by, and I hope to see you back!

Postscript: Wikipedia has a nice article on controlling program flow. It is a bit dense, but for anyone who is interested, go check it out! And while you’re there, you might as well see the article on the switch statement as well.

About these ads
Leave a comment

8 Comments

  1. hello Programming for iOS , i comment your blog , this a nice blog and greatly. Best for me. best … for … Apple content. i going to visit to read and comment your blog.

    Reply
  2. harry

     /  July 16, 2011

    my compiler says “statement requires expression of integer type” (NSString * invalid. see also the authoritative stackoverflow: http://stackoverflow.com/questions/4224495/using-an-nsstring-in-a-switch-statement.

    is this an IOS programming / apple specific mod?

    Reply
  3. harry

     /  July 16, 2011

    my compiler says “statement requires expression of integer type” (NSString * invalid. see also the authoritative stackoverflow: http://stackoverflow.com/questions/4224495/using-an-nsstring-in-a-switch-statement.

    is this an IOS programming / apple specific mod? Also, is it so hard to show use of the isEqualToString: or compare: method ???

    Reply
    • The switch statement only works on enumeration, so it only works with the integer type. Switches are standard C statements, and have not been “updated” to work with Objective-C types. Remember that Obj-C types are pointers; switch compares using the double-equals operator, which wouldn’t work here.

      Reply
  4. embarrassing that this tutorial could be so wrong and lead a bunch of unsuspecting dorks[redacted] down the wrong path.

    Reply
  5. cgchinmay

     /  July 21, 2012

    I always had this doubt,why there is a need of break statement in default case ?Logically default is the last case executed so obviously we would come out of the loop after its execution.

    Reply
  6. Paul

     /  August 9, 2012

    This does not compile. Something like the following will work because char type can be converted to int in C:

    char operator = ‘+’;

    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;
    }

    Reply
  1. Learn Objective-C in 24 Days « Programming for iOS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

  • Welcome

    My goal is to make CupsOfCocoa into a beautiful source for beginners to the iPhone platform to get started. Subscribe below for more, and stay tuned!

  • Contact Me

    If you need to contact me for any reason, feel free to send me an email.
  • The Giving Spirit

    If you've found this site helpful, would you consider donating a little sum? Any amount is appreciated...Thanks so much!

  • Roadmap

  • Enter your email address to follow this blog and receive notifications of new posts by email.

    Join 225 other followers

  • Back to the Past

    November 2010
    S M T W T F S
    « Oct   Dec »
     123456
    78910111213
    14151617181920
    21222324252627
    282930  
  • Time Machine

  • You count!

    • 592,430 views
  • Worldwide Stats

    free counters
Follow

Get every new post delivered to your Inbox.

Join 225 other followers

%d bloggers like this: