Reputation: 364
#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
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