Switch Statements
Multiple equality comparisons
-
In some situations, your program will need to test if a variable is equal to one of several values, and perform a different action based on which value the variable matches
-
For example, you have an
int
variable namedmonth
containing a month number, and want to convert it to astring
with the name of the month. This means your program needs to take a different action depending on whethermonth
is equal to 1, 2, 3, … or 12: -
One way to do this is with a series of
if-else-if
statements, one for each possible value, like this: -
This code is very repetitive, though: every
else if
statement is almost the same, with only the number changing. The text “if(month ==
” is copied over and over again.
Syntax for switch
statements
-
A
switch
statement is a simpler, easier way to compare a single variable against multiple possible values -
It is written like this:
-
First, the “header” of the
switch
statement names the variable that will be compared -
The “body” of the switch statement is enclosed in curly braces, and contains multiple
case
statements -
Each
case
statement gives a possible value the variable could have, and a block of statements to execute if the variable equals that value. Statement block 1 is executed if the variable is equal to value 1, statement block 2 is executed if the variable is equal to value 2, etc. -
The statement “block” within each
case
is not enclosed in curly braces, unlikeif
andelse if
blocks. Instead, it begins on the line after thecase
statement, and ends with the keywordbreak
. -
The
default
statement is like theelse
statement: It defines code that gets executed if the variable does not match any of the values in thecase
statements. -
The values in each
case
statement must be literals, not variables, and they must be unique (you cannot write twocase
statements with the same value)
Example switch
statement
-
This program has the same behavior as our previous example, but uses a
switch
statement instaed of anif-else-if
statement: -
Since the variable in the
switch
statement ismonth
, eachcase
statement means, effectively,if (month == <value>)
. For example,case 1:
has the same effect asif (month == 1)
-
The values in each
case
statement must beint
literals, sincemonth
is anint
-
The
default
statement has the same effect as the finalelse
in theif-else-if
statement: it contains code that will be executed ifmonth
did not match any of the values
switch
with multiple statements
-
So far, our examples have used only one line of code in each
case
-
Unlike
if-else
, you do not need curly braces to put multiple lines of code in acase
-
For example, imagine our “months” program needed to convert a month number to both a month name and a three-letter abbreviation. The
switch
would look like this: -
The computer knows which statements are included in each case because of the
break
keyword. For the “1” case, the block of statements starts aftercase 1:
and ends with thebreak;
aftermonthAbbrev = "Jan";
Intentionally omitting break
-
Each block of code that starts with a
case
statement must end with abreak
statement; it will not automatically end at the nextcase
statement- The
case
statement only defines where code execution starts when the variable matches a value (like an open{
). Thebreak
statement defines where it ends (like a close}
).
- The
-
However, there is one exception: A
case
statement with no body (code block) after it does not need a matchingbreak
-
If there is more than one value that should have the same behavior, you can write
case
statements for both values above a single block of code, with nobreak
between them. If either one matches, the computer will execute that block of code, and then stop at thebreak
statement. -
In a switch statement with this structure:
The statements in block 1 will execute if the variable matches value 1 or value 2, and the statements in block 2 will execute if the variable matches value 3 or value 4.
-
For example, imagine our program needs to tell the user which season the month is in. If the month number is 1, 2, or 3, the season is the same (winter), so we can combine these 3 cases. This code will correctly initialize the string
season
:If
month
is equal to 1, execution will start atcase 1:
, but the computer will continue pastcase 2
andcase 3
and executeseason = "Winter"
. It will then stop when it reaches thebreak
, soseason
gets the value “Winter”. Similarly, ifmonth
is equal to 2, execution will start atcase 2:
, and continue until thebreak
statement, soseason
will also get the value “Winter”. -
This syntax allows
switch
statements to have conditions with a logical OR, equivalent to anif
condition with an||
, likeif(x == 1 || x == 2)
-
For example, the “seasons” statement could also be written as an
if-else-if
with||
operators, like this:
Scope and switch
-
In C#, the scope of a variable is defined by curly braces (recall that local variables defined in a method have a scope that ends with the
}
at the end of the method) -
Since the
case
statements in aswitch
do not have curly braces, they are all in the same scope: the one defined by theswitch
statement’s curly braces -
This means you cannot declare a “local” variable within a
case
statement — it will be in scope (visible) to all the othercase
statements -
For example, imagine you wanted to use a local variable named
nextMonth
to do some local computation within each case in the “months” program. This code will not work:The line
int nextMonth = 3
would cause a compile error because a variable namednextMonth
already exists — the one declared withincase 1
.
Limitations of switch
-
Not all
if-else-if
statements can be rewritten asswitch
statements -
switch
can only test equality, so in general, onlyif
statements whose condition uses==
can be converted toswitch
-
For example, imagine we have a program that determines how much of a fee to charge a rental car customer based on the number of miles the car was driven. A variable named
mileage
contains the number of miles driven, and it is used in thisif-else-if
statement: -
This
if-else-if
statement could not be converted toswitch(mileage)
because of the conditionmileage > 1000
. Theswitch
statement would need to have acase
for each number greater than 1000, which is infinitely many.