#include <iostream>
#include <string>
using namespace std;
// 测试标号只能是常量
void test_switch_const(){
int i = 10;
switch (i) {
case 8: // 标号值必须是常量
cout << 8 << endl;
break;
case 9:
cout << 9 << endl;
break;
case 10:
cout << 10 << endl;
break;
default:
cout << i << endl;
break;
}
}
// 测试在switch中定义变量
// 只能在它的最后一个 case 标号或 default 标号后面定义变量
// 制定这个规则是为避免出现代码跳过变量的定义和初始化的情况
void test_switch_var(){
int i = 11;
switch (i) {
case 8: // 标号值必须是常量
cout << 8 << endl;
//string str = "aa"; // error
break;
case 9:
cout << 9 << endl;
break;
case 10:
cout << 10 << endl;
//string str("aaa"); // error
break;
default:
// 对于有default标号的情况,只能在default中定义变量
string str("aaa"); // ok
cout << str << endl;
cout << i << endl;
break;
}
}
// 在块语句中可以定义变量
// switch只能在使用在整形变量上,string等类类型的对象不能使用switch语句
void test_switch_block(){
char c = 'c';
switch (c) {
case 'c':
{
int i = 10;
cout << 'c' << "_" << i << endl;
}
break;
case 'd':
cout << 'd' << endl;
break;
default:
cout << c << endl;
break;
}
}
switch语句
最新推荐文章于 2022-04-02 14:56:48 发布