01.02.2014 Views

Objective-C Fundamentals

Objective-C Fundamentals

Objective-C Fundamentals

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

304 APPENDIX B The basics of C<br />

}<br />

case South:<br />

NSLog(@"We are heading south");<br />

break;<br />

case East:<br />

NSLog(@"We are heading east");<br />

break;<br />

case West:<br />

NSLog(@"We are heading west");<br />

break;<br />

default:<br />

NSLog(@"We are heading in an unknown direction");<br />

Comparing listing B.1 to listing B.3, you can see that the different syntax and the<br />

amount of whitespace makes a clear impact on the readability and maintainability<br />

of such a statement. One thing worth noticing with switch statements is that<br />

they’re an exception to the general rule that multiple statements must be enclosed<br />

in a set of curly braces. In each case block, it’s possible to simply list multiple statements<br />

one after another, and they’ll all be executed in sequence if their case value<br />

is a match.<br />

In listing B.3 the end of each case block is punctuated by the break keyword,<br />

which signals the end of a particular case block and causes execution to jump to the<br />

end of the entire switch statement. The break keyword is optional; if it isn’t present,<br />

execution follows down into the next statement even if that statement is part of<br />

another case block. This feature is commonly used if you want to handle multiple<br />

potential values in the same or a similar manner. As a somewhat contrived example,<br />

take a look at the following listing.<br />

Listing B.4<br />

switch statement with case statements falling into each other<br />

enum { Horse, Pony, Cat, Kitten } pet = Kitten;<br />

switch (pet)<br />

{<br />

case Kitten:<br />

NSLog(@"This is a young cat so turn on the fire");<br />

// Falls through<br />

case Cat:<br />

NSLog(@"Cats can sleep inthe living room");<br />

break;<br />

}<br />

case Horse:<br />

case Pony:<br />

NSLog(@"These pets don't belong inside the house!");<br />

break;<br />

The code is straightforward in the case of the pet variable storing the value Cat or<br />

Pony. For both values, the switch statement executes the matching calls to NSLog and<br />

then jumps to the end of the switch statement via the break keyword.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!