什么是使用点{
和}
在一个case
声明?通常,无论一条case
语句中有多少行,所有行都将执行。这仅仅是关于旧/新编译器的规则吗?
int a = 0;
switch (a) {
case 0:{
std::cout << "line1\n";
std::cout << "line2\n";
break;
}
}
和
int a = 0;
switch (a) {
case 0:
std::cout << "line1\n";
std::cout << "line2\n";
break;
}
该{}
表示的一个新的块范围。
考虑以下非常人为的示例:
switch (a)
{
case 42:
int x = GetSomeValue();
return a * x;
case 1337:
int x = GetSomeOtherValue(); //ERROR
return a * x;
}
您将收到编译器错误,因为x
已在范围中定义。
将它们分为自己的子作用域将消除x
在switch语句之外进行声明的需要。
switch (a)
{
case 42: {
int x = GetSomeValue();
return a * x;
}
case 1337: {
int x = GetSomeOtherValue(); //OK
return a * x;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句