- 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.
- 深入理解Django:框架內幕與實現(xiàn)原理
- 用戶體驗增長:數(shù)字化·智能化·綠色化
- Secret Recipes of the Python Ninja
- 分布式架構原理與實踐
- Mastering Concurrency in Python
- LabVIEW數(shù)據(jù)采集
- Python數(shù)據(jù)科學實踐指南
- Getting Started with Web Components
- 計算機程序的構造和解釋(JavaScript版)
- 生成藝術:Processing視覺創(chuàng)意入門
- AngularJS Web Application Development Cookbook
- Server Side development with Node.js and Koa.js Quick Start Guide
- Clojure High Performance Programming
- C#程序開發(fā)教程
- 數(shù)據(jù)庫技術及應用(Access)(第2版)