Search code examples
ccompiler-errorsswitch-statementlabellogical-and

Having same expression inside case in switch statement


int main(){
char c='a';
switch(c){
    case 'a' && 1: printf("Hello");
    case 'b' && 1: printf("hey");
                   break;
         default : printf("Goodbye");
          }
}

When I compile this code the result was "compilation error", which (according to me) is because internally both the expression is true and hence for whatever character we take for "c",the constant expression inside for both cases will always be true.

But now comes the doubt that I am not able to understand, how code in interpreted internally and how compiler actually interprets this code?


Solution

  • Both expressions 'a' && 1 and 'b' && 1 have the value 1.

    Therefore your code is strictly equivalent to this:

    ...
    switch(c){
        case 1: printf("Hello");
        case 1: printf("hey");
                       break;
             default : printf("Goodbye");
              }
    }
    ...
    

    Hence the error message because two or more case labels cannot have the same value. The C language does not allow this.