- 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.
推薦閱讀
- Aftershot Pro:Non-destructive photo editing and management
- 網(wǎng)絡(luò)服務(wù)器配置與管理(第3版)
- Linux KVM虛擬化架構(gòu)實戰(zhàn)指南
- 電腦常見問題與故障排除
- Deep Learning with PyTorch
- 電腦高級維修及故障排除實戰(zhàn)
- 超大流量分布式系統(tǒng)架構(gòu)解決方案:人人都是架構(gòu)師2.0
- 單片機(jī)原理及應(yīng)用:基于C51+Proteus仿真
- FreeSWITCH Cookbook
- Zabbix 4 Network Monitoring
- Corona SDK Mobile Game Development:Beginner's Guide
- 電腦主板維修技術(shù)
- 零基礎(chǔ)輕松學(xué)修電腦主板
- FPGA進(jìn)階開發(fā)與實踐
- Windows Presentation Foundation 4.5 Cookbook