6
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.

Dhruva Mehrotra
  • 123
  • 1
  • 12

1 Answers1

13

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.

Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
  • Can this comma operator be useful in any case? I am just asking this 'cause I don't think it is useful in this case. – Dhruva Mehrotra Jun 13 '16 at 07:56
  • 1
    @DhruvaMehrotra Well, that is a broad question. It's yes and no, you never know.There's technically no issue, that's all. – Sourav Ghosh Jun 13 '16 at 07:58
  • @DhruvaMehrotra you can see some cases where it's useful in the duplicate question. Out of those it's rarely useful in C. In C++ you can overload it so many people find a few more useful cases for it http://stackoverflow.com/a/5602236/995714 – phuclv Jun 13 '16 at 08:10
  • The comma operator is usefull, when you define macros – jurhas Jun 13 '16 at 08:14