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.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Dhruva Mehrotra
  • 123
  • 1
  • 12
  • There is a way to make the case statement do two cases if that's what you are asking - just not with a comma. – Jerry Jeremiah Jun 13 '16 at 07:59
  • 1
    @jerry-jeremiah what is that way ,can you please elaborate? – Dhruva Mehrotra Jun 13 '16 at 08:17
  • An occasionally-useful trick is to do something like `switch(PAIR(x, y)) { case PAIR(1, 1): thing1; break; case PAIR(2, 1): thing2; break; case PAIR(1, 2): thing3; break; case PAIR(1, 3): thing4; break; }`, where `PAIR(a, b)` is a macro that expands to something like `10 * a + b`. – Steve Summit Jun 07 '22 at 14:19

1 Answers1

14

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
  • 133,132
  • 16
  • 183
  • 261
  • 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