- C++ Game Development By Example
- Siddharth Shekar
- 269字
- 2021-06-24 14:26:12
Switch statement
The last of the statements is the switch statement. A switch statement checks for several cases of values and if a value matches the expression, then it executes the corresponding statement and breaks out of the switch statement. If it doesn't find any of the values, then it will output a default statement.
The syntax for it looks as follows:
switch( expression){ case constant1: statement1; break; case constant2: statement2; break; . . . default: default statement; break; }
This looks very familiar to the else if statements, but this is more sophisticated. Here is an example:
#include <iostream> #include <conio.h> // Program prints out values to screen int main() { int a = 28; switch (a) { case 1: std::cout << " value of a is " << a << std::endl; break; case 2: std::cout << " value of a is " << a << std::endl; break; case 3: std::cout << " value of a is " << a << std::endl; break; case 4: std::cout << " value of a is " << a << std::endl; break; case 5: std::cout << " value of a is " << a << std::endl; break; default: std::cout << " value a is out of range " << std::endl; break; } _getch(); return 0; }
The output is as follows:

Change the value of a to equal 2 and you will see that it prints out the statement to when case 2 is correct.
Also note that it is important to add the break statement. If you forget to add it, then the program will not break out of the statement.
推薦閱讀
- Learning SQL Server Reporting Services 2012
- SDL Game Development
- 基于Proteus和Keil的C51程序設計項目教程(第2版):理論、仿真、實踐相融合
- Mastering Delphi Programming:A Complete Reference Guide
- 辦公通信設備維修
- 基于Apache Kylin構建大數據分析平臺
- Visual Media Processing Using Matlab Beginner's Guide
- SiFive 經典RISC-V FE310微控制器原理與實踐
- 面向對象分析與設計(第3版)(修訂版)
- 單片機開發與典型工程項目實例詳解
- 電腦橫機使用與維修
- Istio實戰指南
- 單片機項目設計教程
- 從企業級開發到云原生微服務:Spring Boot實戰
- 現代多媒體技術及應用