简体   繁体   English

我可以在C ++中的if语句中使用switch case的大小写

[英]Can I use case of a switch case inside if statement in C++

#include <iostream>
using namespace std;

int main() {
    int a=2,b=2;
    switch(a){
    case 1:
        cout<<"A"<<endl;
        if(b==5){
            case 2:
                cout<<"A"<<endl;
        }
    case 3:
        cout<<"A"<<endl;
    }
    return 0;
}

not able to understand how this code outputs 2 "A"s,how can you put if statement outside of case 无法理解这段代码如何输出2“A”,你怎么能把if语句放在case之外

You don't have a break anywhere, so when case 2 is hit, it falls through to case 3 and prints the second A. 你没有在任何地方break ,所以当case 2被击中时,它会落到case 3并打印第二个A.

If you used different output in each case that would have been a bit more obvious. 如果你在每种情况下使用不同的输出,那将会更加明显。

And yes the grammar lets you put the case inside an if, the same as it allowed duff's device to compile. 是的,语法允许你将case放在if中,就像它允许duff的设备编译一样。

它输出2'A 'A'因为你没有提供break语句。

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

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