有两种情况可以用OR分割表达式吗?

时间:2013-01-28 20:31:17

标签: c

我想使用switch语句,if的条件是:

if (userInput%2 == 0 || userInput != 0)

我是否可以从此代码中获取两个案例,以便为userInput == 0执行不同的操作,为userInput == 0执行不同的操作

case ?:

case ?:

2 个答案:

答案 0 :(得分:3)

您不能,因为值集满足两个条件重叠。具体来说,所有偶数都满足您的条件的两个部分。这就是为什么如果不首先确定条件的哪个部分优先,就不能执行不同的操作。

你可以在switch语句中使用堕落来玩一个小技巧,如下所示:

switch(userInput%2) {
    case 0:
        // Do things for the case when userInput%2 == 0
        ...
        // Note: missing "break" here is intentional
    default:
        if (userInput == 0) break;
        // Do things for the case when user input is non-zero
        // This code will execute when userInput is even, too,
        // because of the missing break.
        ...
}

答案 1 :(得分:2)

为什么不拆分if语句

if (userInput%2 == 0) {
    // something
}
else if (userInput != 0) {
    // something else
}

请注意,测试的顺序很重要,因为所有非零偶数都满足两个测试。