Home > Enterprise >  Having same expression inside case in switch statement
Having same expression inside case in switch statement

Time:06-03

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?

CodePudding user response:

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.

CodePudding user response:

For starters according to the C Standard (6.8.4.2 The switch statement)

3 The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion

In this case labels

case 'a' && 1: printf("Hello");
case 'b' && 1: printf("hey");

there is used the logical AND operator. According to the C Standard (6.5.13 Logical AND operator)

3 The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0. The result has type int.

As the character integer literals 'a' and 'b' and the integer literal 1 are not equal to 0 then the both expressions evaluate to the same integer value 1 at compile time.

So in fact you have

case 1: printf("Hello");
case 1: printf("hey");

As a result the two case labels have the same constant integer expression in the same switch statement. So the compiler issues an error.

Using the logical AND operator containing the operand equal to 1

case 'a' && 1: printf("Hello");
case 'b' && 1: printf("hey");

does not make a sense.

Maybe you mean the following labels

case 'a' & 1: printf("Hello");
case 'b' & 1: printf("hey");

that is labels with the bitwise AND operator.

CodePudding user response:

The case expressions 'a' && 1 and 'b' && 1 both evaluate to 1 because in both cases each operand is non-zero.

This means you have two cases with the same value, which is not allowed.

  • Related