简体   繁体   English

C ++变量在SWITCH语句中DEFAULT后在CASE内初始化

[英]c++ variable initialization inside CASE after DEFAULT in SWITCH statement

I have encountered an interesting peculiarity while playing with code.我在玩代码时遇到了一个有趣的特性。 I am using Eclipse CDT 4.5.2 with Cygwin and C++14 turned on (-std=c++14).我正在使用 Eclipse CDT 4.5.2 并打开 Cygwin 和 C++14 (-std=c++14)。 Variable initialization inside CASE's is normally prohibited, but the following code compiles: CASE 内部的变量初始化通常是被禁止的,但是下面的代码可以编译:

switch( int switchStatement = 11)
{
    default:
        ++j;
        break; // break is optional, still compiles even if omitted
    case 11:
        int caseVariable = 0;
        ++j;
}

If another CASE is added, then exception "jump to case label" is raised.如果添加了另一个 CASE,则会引发异常“跳转到案例标签”。

switch( int switchStatement = 11)
{
    default:
        ++j;
    case 11:
        int caseVariable = 0;
        ++j;
    case 12: // exception
        ++j;
}

Could somebody explain me how it all works?有人能解释一下这一切是如何运作的吗?

why you are getting error in second case but not getting error when you declare a variable in last case statement??为什么在第二种情况下会出错,而在最后一种情况下声明变量时却不会出错??

Because it's a rule of C++ that a jump cannot pass over a variable declaration in the same scope.因为 C++ 的规则是跳转不能越过同一范围内的变量声明。 So when you jump to case 2, you pass over the variable declaration in case 1. But the variable declaration in the last case is OK, because it is never jumped over.所以当你跳到案例 2 时,你跳过了案例 1 中的变量声明。但是最后一个案例中的变量声明是可以的,因为它永远不会被跳过。

The reason for the rule is that if you allowed a jump over a variable declaration it would be very hard for the compiler to work out whether to call a destructor for that variable.该规则的原因是,如果您允许跳过变量声明,编译器将很难确定是否为该变量调用析构函数。 If you had jumped over the variable declaration you would not need to call the destructor, if you had not jumped then you would.如果你跳过了变量声明,你就不需要调用析构函数,如果你没有跳过,那么你会调用析构函数。

The Variable declared and initialized in one case statement can still be visible in other case block but they will not be initialized because the initialization code belongs to another case.在一个 case 语句中声明和初始化的变量仍然可以在另一个 case 块中可见,但它们不会被初始化,因为初始化代码属于另一个 case。

In C++ Problem is of scope.在 C++ 中,问题是范围的。 Here, case statements are "labels".在这里,case 语句是“标签”。 Hence, compiler will treat them for making jump from one statement to another.因此,编译器会将它们视为从一个语句跳转到另一个语句。 In this particular example, compiler won't understand how to proceed further.在这个特定的例子中,编译器不会理解如何进一步进行。 To solve this problem you can include the code inside the case into a {} block.要解决此问题,您可以将案例中的代码包含在 {} 块中。 The extra { and } mean that the compiler has no trouble working out when to call destructor.额外的 { 和 } 意味着编译器可以轻松确定何时调用析构函数。 Therefore, providing scope or curly brackets to that particular case statement while declaring new variables is important.因此,在声明新变量时为该特定 case 语句提供范围或大括号很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM