Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In c, can a switch statement have 2 arguments? [duplicate]

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.

like image 923
Dhruva Mehrotra Avatar asked Jun 13 '16 07:06

Dhruva Mehrotra


People also ask

Can switch take two arguments?

A switch statement may only have one default clause; multiple default clauses will result in a SyntaxError .

Can we pass 2 arguments in switch-case?

No. The cases only apply to the one variable that can be specified in the switch statement.

Can switch-case have multiple conditions in C?

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.

Can switch-case have multiple values?

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.


1 Answers

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.

like image 127
Sourav Ghosh Avatar answered Oct 19 '22 11:10

Sourav Ghosh