passing multiple values to switch separating the v

2020-04-21 08:06发布

问题:

Can I pass multiple values to the switch case statement separating different values by commas ? what would the expression evaluate to? If no error occurs, which of the multiple values would the compiler evaluate the switch with ? Keeping in mind the low precedence of the comma operator? say for instance i write the code as follows:

int m=10;
switch(m, m*2)
{
     case 10: printf("\n case 10");
     case 20: printf("\n case 20");
     case 30: printf("\n case 30");
     default: printf("\n no case");
 }

回答1:

The comma operator evaluates all the expressions and returns the value of the rightmost one. (It doesn't make any difference that you're using it in a switch.)

Your example is exactly the same as switch (m*2), but if any of the preceding expressions had side effects, those side effect would be applied before the switch statement was executed.