How to write "if x equals 5 or 4 or 78 or..." in C

22,970

Solution 1

First, you're using assignments not equality tests in your ifs. The first method (with suitable substitutions for equality) is the best way to do the test, though if you have a lot of possible options, there might be better ways. The second way might compile, but it won't do what you want, it will always return true since both 4 and 78 evaluate to true and what you are doing is evaluating whether 5 (the result of assigning 5 to x) or 4 or 78 are true. A switch statement might be one possible alternative.

switch (x) {
    case 4:
    case 5:
    case 78:
       blah...
       break;
    default:
}

Solution 2

There's no shortcut for the if statement, but I suggest considering:

switch (x)
{
    case 4: 
    case 5:
    case 78:
        /* do stuff */
        break;

    default:
        /* not any of the above... do something different */
}

Solution 3

No you cannot and the test for equality is ==, not =

Solution 4

@uncle brad is spot on, but later you'll probably learn about something called a switch statement. It looks funky but is often used in these sorts of situations (where several possible values of a variable all have the same effect):

switch (x) {
case 4:
case 5:
case 78:
    // ...
    break;
}

Though you'd only want to use a switch statement when the meaning of an if statement is less clear--most compilers these days are smart enough to generate optimal machine code either way.

Share:
22,970
stockoverflow
Author by

stockoverflow

Updated on July 05, 2022

Comments

  • stockoverflow
    stockoverflow almost 2 years

    I have a quick question about using logical operators in an if statement.

    Currently I have an if statement that checks if x equals to 5 or 4 or 78:

    if ((x == 5) || (x == 4) || (x == 78)) {
    blah
    }
    

    And I was wondering if I could just condense all that to:

    if (x == 5 || 4 || 78) {
    blah
    }
    

    Sorry for such a basic question, I've just started learning C.