int main()
{
switch(1,2)
{
case 1:printf("1");break;
case 2:printf("2");break;
default: printf("error");break;
}
}
Is this valid in c?
I thought it shouldn't be , but when I compiled it , it shows no error and produces output 2.
A switch statement may only have one default clause; multiple default clauses will result in a SyntaxError .
No. The cases only apply to the one variable that can be specified in the switch statement.
In C++, the switch statement is used for executing one condition from multiple conditions. It is similar to an if-else-if ladder. Switch statement consists of conditional based cases and a default case. In a switch statement, the “case value” can be of “char” and “int” type.
The switch can includes multiple cases where each case represents a particular value. Code under particular case will be executed when case value is equal to the return value of switch expression. If none of the cases match with switch expression value then the default case will be executed.
Yes, this is valid, because in this case, the ,
is a comma operator.
Quoting C11
, chapter §6.5.17, Comma operator, (emphasis mine)
The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.
This (evaluates and) discards the left operand and uses the value of the right (side) one. So, the above statement is basically the same as
switch(2)
Just to elaborate, it does not use two values, as you may have expected something like, switching on either 1 or 2.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With