在switch case内声明一个变量

4

在 switch-case 中不同 case 内部声明相同变量名时,为什么会出现警告?

switch()
{
   case 1:
     int a;
   break;

   case 2:
     int a;
   break;

}

有没有一种方法可以在不收到警告的情况下完成这个操作?(不是把它放在 switch - case 之前)

2
我认为这不仅是一个警告,而是一个错误。两个变量具有相同的作用域和名称。您可以为每种情况使用一个作用域。 - mch
2
创建一个由花括号 {} 包围的代码块。 - Some programmer dude
2
将花括号放在case 1: {...}周围。 - Shubham
可能是为什么不能在switch语句中声明变量?的重复问题。 - Umaiki
1
@Umaiki:这不是那个问题的副本。他们问了不同的问题。 - Eric Postpischil
switch(...) { int a; case ... } - William Pursell
3个回答

11

这是因为两个声明的词法作用域是整个 switch 语句体,所有的 case 都共享该作用域。
也就是说,在词法作用域方面,它就像是写了:

{
    int a;
    int a;
}
解决方法是将声明放在另一个括号范围内。

解决方法是将声明放在另一个括号范围内。

switch(whatever)
{
   case 1:
   {
     int a;
     break;
   }

   case 2:
   {
     int a;
     break;
   }
}

无论您是将break语句放在括号内还是外面,这主要是个人口味的问题。我更喜欢将整个情况包含在内。

这种方法之所以有效,与此“无开关”片段的原因相同:

{
    {
        int a;
    }
    {
        int a;
    }
}

3

在一个新的代码块内声明您的变量。使用{开始一个新的代码块。

switch()
{
   case 1:
   {
     int a;
      break;
    }

   case 2:
   {
     int a;
      break;
   }
}

1

有两个原因。

  • 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
    }
    
最好的解决方案是为每个情况创建另一个本地作用域,或者重命名变量。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接