在 switch-case 中不同 case 内部声明相同变量名时,为什么会出现警告?
switch()
{
case 1:
int a;
break;
case 2:
int a;
break;
}
有没有一种方法可以在不收到警告的情况下完成这个操作?(不是把它放在 switch - case 之前)
在 switch-case 中不同 case 内部声明相同变量名时,为什么会出现警告?
switch()
{
case 1:
int a;
break;
case 2:
int a;
break;
}
这是因为两个声明的词法作用域是整个 switch 语句体,所有的 case 都共享该作用域。
也就是说,在词法作用域方面,它就像是写了:
{
int a;
int a;
}
解决方法是将声明放在另一个括号范围内。
解决方法是将声明放在另一个括号范围内。
switch(whatever)
{
case 1:
{
int a;
break;
}
case 2:
{
int a;
break;
}
}
无论您是将break
语句放在括号内还是外面,这主要是个人口味的问题。我更喜欢将整个情况包含在内。
这种方法之所以有效,与此“无开关”片段的原因相同:
{
{
int a;
}
{
int a;
}
}
在一个新的代码块内声明您的变量。使用{
开始一个新的代码块。
switch()
{
case 1:
{
int a;
break;
}
case 2:
{
int a;
break;
}
}
有两个原因。
Everything inside the { ... }
of a switch
resides in the same scope, unless you add further local scopes inside it. So you can't have two variables with the same name, for the same reason as you can't have:
int main (void)
{
int a; int a; // will not compile
}
Grammatically, case x:
works like a label. In the C syntax, it is formally called labeled-statement and a labeled-statement can only be followed by a statement, not a declaration. So you can't have a variable declaration directly after case x:
, for the same reason as you can't have
int main (void)
{
label: int a; // will not compile
}
{}
包围的代码块。 - Some programmer dudecase 1: {...}
周围。 - Shubhamswitch(...) { int a; case ... }
- William Pursell