Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to split expression with OR, to two cases?

Tags:

c

I want to use a switch statement, and my condition fot the if is:

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

Can I get two cases from this code to execute different actions for userInput == 0 and different one for userInput == 0

case ?:

case ?:
like image 890
MNY Avatar asked Dec 06 '25 08:12

MNY


1 Answers

You cannot, because the value sets satisfying the two conditions overlap. Specifically, all even numbers satisfy both parts of your conditions. That is why you cannot perform different actions without deciding first which part of the condition takes precedence.

You can play a little trick with fall-through inside the switch statement, like this:

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.
        ...
}
like image 130
Sergey Kalinichenko Avatar answered Dec 08 '25 21:12

Sergey Kalinichenko