官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 犍为县| 恩施市| 蓝山县| 花垣县| 方城县| 拉孜县| 汾西县| 肥城市| 石嘴山市| 怀宁县| 黎城县| 阜南县| 靖西县| 勐海县| 娱乐| 乌什县| 抚顺市| 界首市| 光山县| 和龙市| 夏津县| 临颍县| 黑水县| 吴堡县| 左贡县| 金昌市| 怀远县| 乌拉特前旗| 安陆市| 中牟县| 新绛县| 丰宁| 宣威市| 齐河县| 嘉鱼县| 兴海县| 耒阳市| 汾阳市| 和政县| 慈溪市| 普兰县|