< Previous | Contents | Next >
You can use a switch statement to create multiple branching points in your code. Here’s a generic form of the switch statement:
switch (choice)
{
case value1: statement1;
break;
case value2: statement2;
break;
case value3: statement3;
break;
.
.
.
case valueN: statementN;
break;
default: statementN + 1;
}
The statement tests choice against the possible values—value1, value2, and value3—in order. If choice is equal to a value, then the program executes the corresponding statement. When the program hits a break statement, it exits the switch structure. If choice doesn’t match any value, then the statement associated with the optional default is executed.
The use of break and default are optional. If you leave out a break, however, the program will continue through the remaining statements until it hits a break or a default or until the switch statement ends. Usually you want one break statement to end each case.
52 Chapter 2 n Truth, Branching, and the Game Loop: Guess My Number
Hi n t
Although a default case isn’t required, it’s usually a good idea to have one as a catchall.
Here’s an example to cement the ideas. Suppose choice is equal to value2. The program will first test choice against value1. Because they’re not equal, the program will continue. Next, the program will test choice against value2. Because they are equal, the program will execute statement2. Then the program will hit the break statement and exit the switch structure.
Tra p
You can use the switch statement only to test an int (or a value that can be treated as an int, such as a char or an enumerator). A switch statement won’t work with any other type.