c++switch-statementlabelcase

what is the difference between using the same value for two case labels and using several case labels for a single case?


I was reading from Bjarne's Programming and Principles using C++.

I ran into the following details about switch:

You can use several case labels for a single case.

You cannot use the same value for two case labels.

I think I clearly understand the 2. one. It should mean that:

switch (a) {

  case 'c':{//some code} 

  case 'c':{//some (different) code} 
} 

Is not legal.

However, I am not sure if the first one means, that if case no.1 and case no.2 and so on are different then I can have any number of cases(, of course them being constant expressions) or it means that I can have any number of cases, but some of them doing the same thing.

I have found a similar question regarding this: multiple label value in C switch case

Do I interpret it right? If not, what is it I am missing or get wrong?


Solution

  • This is allowed:

    switch ( expression )
    {
        case 1:
        case 2: 
        case 3:
              //some code
              break;
        //...
    }
    

    And this is NOT allowed:

    switch ( expression )
    {
        case 1:
              //some code
              break;
        case 1:
              //some other code
              break;
        //...
    }   
    

    So, it's not allowed to use the same value for two or more case labels.