问题描述
在案例$中使用
{
和}
c $ c>语句?通常,无论 case
语句中有多少行,所有行都被执行。这是只是一个关于旧的/较新的编译器的规则,还是有背后的事情?
What is the point with using {
and }
in a case
statement? Normally, no matter how many lines are there in a case
statement, all of the lines are executed. Is this just a rule regarding older/newer compilers or there is something behind that?
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;
}
推荐答案
请考虑以下非常有用的示例: Consider the following very contrived example: 你会得到一个编译错误,因为 You will get a compiler error because 将这些分隔到自己的子范围将不再需要声明 Separating these to their own sub-scope will eliminate the need to declare 这篇关于在case语句中使用{}。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!switch (a)
{
case 42:
int x = GetSomeValue();
return a * x;
case 1337:
int x = GetSomeOtherValue(); //ERROR
return a * x;
}
x
已在范围中定义。
x
is already defined in the scope. x
在switch语句之外。
x
outside the switch statement.switch (a)
{
case 42: {
int x = GetSomeValue();
return a * x;
}
case 1337: {
int x = GetSomeOtherValue(); //OK
return a * x;
}
}