42 Switch Statements

It is not uncommon to check a variable for a set of values. Using if-else statements, it would look like this:

i​n​t​ ​y​e​a​s​t​T​y​p​e​ ​=​ ​.​.​.​;​

i​f​ ​(​y​e​a​s​t​T​y​p​e​ ​=​=​ ​1​)​ ​{​
 ​ ​ ​m​a​k​e​B​r​e​a​d​(​)​;​
}​ ​e​l​s​e​ ​i​f​ ​(​y​e​a​s​t​T​y​p​e​ ​=​=​ ​2​)​ ​{​
 ​ ​ ​m​a​k​e​B​e​e​r​(​)​;​
}​ ​e​l​s​e​ ​i​f​ ​(​y​e​a​s​t​T​y​p​e​ ​=​=​ ​3​)​ ​{​
 ​ ​ ​m​a​k​e​W​i​n​e​(​)​;​
}​ ​e​l​s​e​ ​{​
 ​ ​ ​m​a​k​e​F​u​e​l​(​)​;​
}​

To make this sort of thing easier, C has the switch statement. The code above could be changed to this:

i​n​t​ ​y​e​a​s​t​T​y​p​e​ ​=​ ​.​.​.​;​ s​w​i​t​c​h​ ​(​y​e​a​s​t​T​y​p​e​)​ ​{​ ​ ​ ​ ​c​a​s​e​ ​1​:​ ​ ​ ​ ​ ​ ​ ​ ​m​a​k​e​B​r​e​a​d​(​)​;​ ​ ​ ​ ​ ​ ​ ​ ​b​r​e​a​k​;​ ...

Get Objective-C Programming: The Big Nerd Ranch Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.