Tutorial Details:
Difficulty Level:
Intermediate
Topics Covered: Using
the switch statement to make decisions.
Assumed Knowledge:
The Basics, My First Program, Constants and Variables,
Conditionals (if)
Written By: BILL LANE
Print Version
As we discussed in Conditional (If) it is very important
to have a method to make decisions once our program is running.
There is an excellent alternative to the if
statement in the form of the switch
statement. switch is ideal
when there are a number of possible options and is a lot neater
than using nested if statements
(that is if's inside if's inside if's). But it only works
when you know exactly what the values will be. You can't use
switch to check if a value
is greater than, or less than another value. So let's consider
a situation where you would use switch.
Let's imagine you are building a mission that has a number
of distinct stages. There may be a setup stage, a normal running
stage, a I've been hit stage, a mission successful stage and
a time up stage. You would typically assign a number to represent
these different stages and have a variable to keep track of
the current value. You could then use a switch
statement in your code to determine the current game state
and respond in an appropriate manner. Let's see how this might
work:
switch (gGameState)
{
case 1: PlaySound(1); break;
case 2: PlaySound(2); break;
case 3: PlaySound(3); break;
default: PlaySound(4); break;
}
In this example, we start with the switch
keyword and then we have the name of the value we want to
check in brackets. I'm checking on a global variable (hence
the g at the start) gGameState. This is followed by an opening
curly brace, with the closing curly brace encompassing a series
of case statements.
The case statements are
simple enough. The first case
statement basically says that if gGameState equals 1 then
play sound 1. The code checks each line and if it finds a
match it executes the commands. I've just used one command,
but there can be multiple commands spanning many lines for
each option. Note the break
keyword at the end of each command. This tells the program
to break out of (not continue checking) the rest of the cases.
Also note the default
keyword after the last case.
It tells the program that if nothing else matches then it
must use this command. It is optional and so may be omitted.
If you don't include a default and none of the cases match
then the program will continue on.
The switch statement is very straight forward. But it's also
incredibly useful. So keep it in mind in case you need to
make an important decision.
|