- Beginning C++ Game Programming
- John Horton
- 509字
- 2021-03-26 16:12:29
Making decisions with switch
We have already looked at if, which allows us to decide whether to execute a block of code based upon the result of its expression. But sometimes, a decision in C++ can be made in other ways that are better.
When we must make a decision based on a clear list of possible outcomes that don't involve complex combinations or wide ranges of values, then switch is usually the way to go. We can start a switch decision as follows:
switch(expression)
{
// More code here
}
In the previous example, expression could be an actual expression or just a variable. Then, within the curly braces, we can make decisions based on the result of the expression or value of the variable. We do this with the case and break keywords:
case x:
//code for x
break;
case y:
//code for y
break;
As you can see, each case states a possible result and each break denotes the end of that case and the point that the execution leaves the switch block.
Optionally, we can also use the default keyword without a value to run some code in case none of the case statements evaluate to true, as follows:
default: // Look no value
// Do something here if no other case statements are true
break;
As a final and less abstract example for switch, consider a retro text adventure where the player enters a letter such as "n", "e", "s", or "w" to move North, East, South, or West. A switch block could be used to handle each possible input from the player:
// get input from user in a char called command
switch(command){
case 'n':
// Handle move here
break;
case 'e':
// Handle move here
break;
case 's':
// Handle move here
break;
case 'w':
// Handle move here
break;
// more possible cases
default:
// Ask the player to try again
break;
}
The best way of understanding all we have seen regarding switch is by putting it into action, along with all the other new concepts we are learning about.
Next, we will learn about another C++ concept we need to understand before we write some more code. Let's look at class enumerations.