我一直在想这个问题——为什么不能在switch语句的case标签后面声明变量呢?在c++中,你可以在任何地方声明变量(并且在第一次使用时声明它们显然是一件好事),但以下仍然不能工作:

switch (val)  
{  
case VAL:  
  // This won't work
  int newVal = 42;  
  break;
case ANOTHER_VAL:  
  ...
  break;
}  

上面给了我以下错误(MSC):

'newVal'的初始化被'case'标签跳过

这在其他语言中似乎也是一个限制。为什么这是一个问题?


当前回答

这个问题的答案是我写的。然而,当我完成它,我发现答案已经关闭。所以我把它贴在这里,也许喜欢参考标准的人会发现它很有用。

问题的原始代码:

int i;
i = 2;
switch(i)
{
    case 1: 
        int k;
        break;
    case 2:
        k = 1;
        cout<<k<<endl;
        break;
}

实际上有两个问题:

1. 为什么我可以在case标签后声明一个变量?

这是因为在c++中标签必须是这样的:

N3337 6.1/1

标记语句: … 属性说明符-seqopt case常量表达式:语句 …

在c++中声明语句也被认为是语句(与C相反):

N3337 6/1:

声明: ... 说明语句 ...

2. 为什么我可以跳过变量声明,然后使用它?

因为: N3337 6.7 / 3

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps (The transfer from the condition of a switch statement to a case label is considered a jump in this respect.) from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer (8.5).

因为k是标量类型,并且在声明时没有初始化,跳过它的声明是可能的。这在语义上是等价的:

goto label;

int x;

label:
cout << x << endl;

然而,如果x在声明点初始化,这将是不可能的:

 goto label;

    int x = 58; //error, jumping over declaration with initialization

    label:
    cout << x << endl;

其他回答

整个switch语句在同一个作用域中。要解决这个问题,可以这样做:

switch (val)
{
    case VAL:
    {
        // This **will** work
        int newVal = 42;
    }
    break;

    case ANOTHER_VAL:
      ...
    break;
}

注意括号。

newVal存在于开关的整个作用域中,但只有在VAL分支被命中时才会初始化。如果你在VAL中创建一个代码块,它应该是OK的。

有趣的是,这很好:

switch (i)  
{  
case 0:  
    int j;  
    j = 7;  
    break;  

case 1:  
    break;
}

... 但这不是:

switch (i)  
{  
case 0:  
    int j = 7;  
    break;  

case 1:  
    break;
}

我得到一个修复足够简单,但我不明白为什么第一个例子不打扰编译器。正如之前所提到的(2年前的呵呵),声明不是导致错误的原因,即使有逻辑。初始化是问题所在。如果变量在不同的行上被初始化和声明,它将被编译。

试试这个:

switch (val)
{
    case VAL:
    {
        int newVal = 42;
    }
    break;
}

匿名对象似乎可以在switch case语句中声明或创建,因为它们不能被引用,因此不能进入下一个case。考虑这个例子是在GCC 4.5.3和Visual Studio 2008上编译的(可能是一个遵从性问题,所以请专家们权衡一下)

#include <cstdlib>

struct Foo{};

int main()
{
    int i = 42;

    switch( i )
    {
    case 42:
        Foo();  // Apparently valid
        break;

    default:
        break;
    }
    return EXIT_SUCCESS;
}