Is it possible to split an OR expression into two cases?
I want to use a switch statement and my fot if condition is:
if (userInput%2 == 0 || userInput != 0)
Is it possible to get two cases from this code to do different things for userInput == 0
and another foruserInput == 0
case ?:
case ?:
You cannot, because the set of values that meet two conditions overlaps. In particular, all even numbers satisfy both sides of your condition. This is why you cannot perform different actions without first deciding which part of the condition takes precedence.
You can play a little dip inside the operator trick switch
, for example:
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.
...
}
Why not just split the operator if
if (userInput%2 == 0) {
// something
}
else if (userInput != 0) {
// something else
}
Note that the order of the tests will be important, since all nonzero even numbers satisfy both tests.