为什么不能在switch语句中声明变量? [英] Why can’t variables be declared in a switch statement?

查看:501
本文介绍了为什么不能在switch语句中声明变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想进一步了解「为什么不能变量在switch语句中声明?

I want to know more about "Why can’t variables be declared in a switch statement?"

我阅读了这篇文章,但我没有得到它。
你可以在switch中声明变量,但是decalre和初始化一个变量或者声明类的对象给它一个合适的时间错误。

I read the post but i am not getting it exactly. You can just declare variable inside switch but to decalre and initialize a variable or to declare object of class it gives complie time error.

请解释我....

推荐答案

如果未命中包含变量初始化的标签,则将跳过变量的初始化。这将是不好的,因为编译器然后必须发出代码,当且仅当初始化代码已经运行时才会销毁该变量。

Essentially because the initialisation of the variable would be skipped if the label containing the variable initialisation was not hit. This would be bad because the compiler would then have to emit code that would destroy said variable if and only if the initialisation code had run.

例如:

class A
{
  // has some non-trivial constructor and destructor
};

switch (x)
{
  case 1:
    A a;
    break;
  default:
    // do something else
}

代码已经达到默认,那么 a 将不会被初始化。编译器必须能够预先弄清楚这一点。可能是因为性能原因,这是不允许的。

If the code had hit the default, then a would not have been initialised. The compiler would have to have been able to figure this out in advance. Probably for performance reasons, this was disallowed.

简单的修复是引入一个新的范围层:

The simple fix is to introduce a new layer of scope:

class A
{
  // has some non-trivial constructor and destructor
};

switch (x)
{
  case 1:
    {
      A a;
    }
    break;
  default:
    // do something else
}

确定, a 的破坏现在已经很好定义。

This makes it ok, the destruction of a is now well defined.

这篇关于为什么不能在switch语句中声明变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆