When a case of switch
does not include break
, all subsequent cases are executed until finding a break
, so in your case:
switch(car1){
case 'a':cout<<"es la letra A o B\n";
case 'b':cout<<"es la letra A o B\n";
}
When car1
is 'a'
the message "es la letra A o B\n"
will be written twice (the case of 'a'
and then follow and write the case of 'b'
. When car1
is 'b'
the message it will be written once.
Therefore:
switch(car1){
case 'a':
case 'A':
case 'b':
case 'B':
cout<<"es la letra A o B\n";
}
It will print the same message, once, when car1
is a
, b
, A
or B
. Some compilers emit an alarm with the previous code, to avoid it add the attribute [[fallthrough]]
switch(car1){
case 'a':
[[fallthrough]];
case 'A':
[[fallthrough]];
case 'b':
[[fallthrough]];
case 'B':
cout<<"es la letra A o B\n";
}