传递多个值以切换以逗号分隔值 [英] passing multiple values to switch separating the values by commas
问题描述
我可以将多个值传递给用逗号分隔不同值的 switch case 语句吗?表达式的计算结果是什么?如果没有发生错误,编译器将使用多个值中的哪一个来评估开关?记住逗号运算符的低优先级?比如说我写代码如下:
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("
case 10");
case 20: printf("
case 20");
case 30: printf("
case 30");
default: printf("
no case");
}
推荐答案
逗号运算符计算所有表达式并返回最右边的值.(在 switch
中使用它没有任何区别.)
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
.)
您的示例与 switch (m*2)
完全相同,但如果前面的任何表达式有副作用,则这些副作用将在 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.
这篇关于传递多个值以切换以逗号分隔值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!