In c, can a switch statement have 2 arguments?

int main() { switch(1,2) { case 1:printf("1");break; case 2:printf("2");break; default: printf("error");break; } } 

Is this really in c?

I thought this should not be, but when I compiled it, it does not show errors and produces output 2.

+6
source share
1 answer

Yes, this is true, because in this case , is a comma .

Citation C11 , chapter Β§6.5.17, Comma-operator, (emphasis added)

The left operand of the comma operator is evaluated as a void expression; There is a point in the sequence between its evaluation and the point of the correct operand. Then the right operand is evaluated; The result has its type and meaning.

This (evaluates and) discards the left operand and uses the value of the right (side). So, the above statement basically coincides with

 switch(2) 

To clarify, it does not use two values, as you might have expected something like the inclusion of 1 or 2.

+13
source

All Articles