switch with cases of many possibilities

1

I have a question.

switch(car1){
   case 'a':cout<<"es la letra A o B\n";
   case 'b':cout<<"es la letra A o B\n";
}

In this case, is it possible that when the cases are put, when you want car1 to be to or b say the message instead of having to write each case ?

    
asked by karantooo 11.10.2018 в 00:24
source

2 answers

5

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";
}
    
answered by 11.10.2018 в 07:58
1

If what you want is that in either case (A or B) print the message you should only place

case 'a':  
case 'b':cout<<"es la letra A o B\n";  
         break;  

Because if 'a' is going to continue until you find some break; that breaks the switch , if you put it on both sides (as you have it) it will impimpress 2 times the message if the letter is' a'o 1 time only if it's 'b'

    
answered by 11.10.2018 в 00:30