thisisbhavin
thisisbhavin

Reputation: 364

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

Upvotes: 1

Views: 2324

Answers (2)

Colin
Colin

Reputation: 3524

You don't have a break anywhere, so when case 2 is hit, it falls through to case 3 and prints the second 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.

Upvotes: 3

Mike
Mike

Reputation: 1215

It outputs 2 'A's since you provide no break statement.

Upvotes: -1

Related Questions