简体   繁体   English

使用不带开关的案例,请解释此代码的output

[英]Use of case without switch, please explain the output of this code

We use cases with switch.我们使用带有开关的案例。 But here the cases are inside the default case, so it should require one more switch.但是这里的情况是在默认情况下,所以它应该需要一个更多的开关。 But the code doesn't give any compile time errors.但是代码没有给出任何编译时错误。

#include<iostream>
int main()
{
    int num=4;
    while (num)
    {
        switch(num)
        {

            default:
                case 1:
                    std::cout<<"Executing "<<num<<"\n";
                
                case 2:
                
                case 3:
    
                break;
        }
        num--;          
    }
    return 0;
}

Moreover the output is Executing 4 and then Executing 1. According to me the output should be Executing 1 because each time default is being entered.此外,output 正在执行 4,然后执行 1。根据我的说法,output 应该是 Executing 1,因为每次都输入默认值。 It will enter case 1 when value is 1. But first please explain how this is compiling, because according to me there should be a nested switch.当值为 1 时它将进入 case 1。但首先请解释这是如何编译的,因为根据我的说法应该有一个嵌套开关。

In a switch , all case and default are at the same level, you were just caught by the (stupid?) indentation, and a rather inconsistent use of default.switch中,所有casedefault都处于同一级别,您只是被(愚蠢的?)缩进所吸引,并且默认使用相当不一致。 In fact it should read:实际上它应该是:

    switch(num)
    {
            default:
            case 1:
                std::cout<<"Executing "<<num<<"\n";
            
            case 2:
            case 3:
                break;
    }

Meaning: do nothing (break) if 2 or 3, and display Executing... for 1 or any other value.含义:如果为 2 或 3,则不执行任何操作(中断),并显示Executing...为 1 或任何其他值。

This would do the same and would be IMHO more readable:这将做同样的事情并且恕我直言更具可读性:

    switch(num)
    {
        case 2:
        case 3:
            break;

        default:
            std::cout<<"Executing "<<num<<"\n";
    }

case 1 to 3 are indented wrongly. case 1 到 3 缩进错误。

It's a so-called "fallthrough".这就是所谓的“跌倒”。 If the switch hits the default case, it will fall through until it reaches a break meaning it will execute other cases on the way.如果开关达到default情况,它将失败,直到达到中断,这意味着它将在途中执行其他情况。
In your case, if it hits the default case, it will execute case 1 , case 2 and case 3在您的情况下,如果它达到default情况,它将执行case 1case 2case 3

Edit: I recommend ending each case with a break and putting default as the last case.编辑:我建议以break结束每个案例并将default为最后一个案例。 Only if you really want to fallthrough and know what you do you could omit the break .只有当你真的想失败并知道你在做什么时,你才能省略break

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

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