C++ switch语句
C++ switch语句从多个条件执行一个语句。 它就类似于在C++中的if-else-if语句。
switch语句的基本语法如下所示 -
switch(expression){ case value1: //code to be executed; break; case value2: //code to be executed; break; ...... default: //code to be executed if all cases are not matched; break; }
switch语句的执行流程如下图所示 -
C++ Switch示例
#include <iostream> using namespace std; int main () { int num; cout<<"Enter a number to check grade:"; cin>>num; switch (num) { case 10: cout<<"It is 10"<<endl; break; case 20: cout<<"It is 20"<<endl; break; case 30: cout<<"It is 30"<<endl; break; default: cout<<"Not 10, 20 or 30"<<endl; break; } return 0; }执行上面代码,得到以下结果 -
[codeinn@localhost cpp]$ g++ swith.cpp [codeinn@localhost cpp]$ ./a.out Enter a number to check grade:69 Not 10, 20 or 30 [codeinn@localhost cpp]$ ./a.out Enter a number to check grade:89 Not 10, 20 or 30 [codeinn@localhost cpp]$ ./a.out Enter a number to check grade:10 It is 10
本站文章除注明转载外,均为本站原创或编译
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创优秀实例教程
转载请注明:文章转载自:代码驿站 [http:/www.codeinn.net]
本文标题:C++ switch语句
本文地址:http://www.codeinn.net/cplus/1726.html
欢迎任何形式的转载,但请务必注明出处,尊重他人劳动共创优秀实例教程
转载请注明:文章转载自:代码驿站 [http:/www.codeinn.net]
本文标题:C++ switch语句
本文地址:http://www.codeinn.net/cplus/1726.html