作用:执行多条件分支语句
语法:
switch(表达式) { case 结果1: 执行语句;break; case 结果2: 执行语句;break; case 结果3: 执行语句;break; ... default: 执行语句;break; }
注意:
1) case中如果没有break,那么程序会一直向下执行
2) switch分支判断里,case关键字后只能是整型或者字符型
switch (a) { case a > 6 && a < 15 : cout << "222" << endl; break; //报错,必须是整型或字符型 case 10 : cout << "111" << endl; break; default:break; }
总结:
与if语句比较,switch语句结构清晰,执行效率高,但不可以指定区间,而if语句是可以在条件里指定区间的