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

12

6

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.

Parik answered 16/3, 2011 at 3:16 Comment(5)
@stockoverflow, no you cannot do that. You must check one condition against only one other condition and connect them with or || operators. Also your = needs to be ==.Svoboda
COBOL has a shortcut like that. But I don't think you want to go there.Overall
Haha, yeah I sure don't. Our lecturer only lets us use simple conditional stuff since everyone is beginning C. Any reason why this kind of shortcut isn't allowed in C?Parik
You can't use this shortcut because it is perfectly valid C code as you wrote it (ignoring the 'blah' part). It just doesn't do what you think it should.Spirituality
@Parik - Probably because it would have made writing the initial C compilers significantly more complicated. And the operator precedences would have been much harder to do correctly to make statements like that work. Under C's precedence rules x == 4 || 5 parses as (x == 4) || 5, while the shortcut you suggest would require it to parse as x == (4 || 5), which would require other, arguably more common operations (like x == 0 || y == 0) to use more parentheses.Nettle
O
10

There is no shortcut, but you need to fix your equality operator.

if ((x == 5) || (x == 4) || (x == 78)) {
Overall answered 16/3, 2011 at 3:18 Comment(1)
I "There is no shortcut" statement still valid?Divaricate
R
6

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:
}
Rambort answered 16/3, 2011 at 3:22 Comment(0)
G
3

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 */
}
Gudrunguelderrose answered 16/3, 2011 at 3:23 Comment(0)
A
2

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

Amide answered 16/3, 2011 at 3:18 Comment(0)
S
1

@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.

Sfumato answered 16/3, 2011 at 3:21 Comment(2)
Looks way more simple, can't wait to get into the advanced stuff thanks for the tip.Parik
@Parik switch statements are far from being the advanced stuff. Also, no one has pointed out that x == 5 || 4 || 78 is a perfectly valid C statement but it doesn't mean what you want it to mean. In C, any expression can be used in a boolean context; it means true if non-zero and false if zero. 4 is non-zero so that expression is always true. You should get yourself a good C book, read through it and do all the exercises (which should include questions like "What's the value of x == 5 || 4?"), and then ask questions about things the book doesn't cover.Safar
W
1

It's been answered in the time it took me to log in, but you could use the switch, and break it out into a function

int isValid(int toCheck) {
   switch(toCheck) {
      case 4:
      case 5:
      case 78: 
         return 1;
      default:
         return 0;
   }
}

Then you would just call the method every time you needed to check the int against the established cases.

Admittedly, this example is rather silly, but for a bigger selection of cases, and ones that were evaluated repeatedly, you could do something like this to simplify and reuse some code.

Wingfield answered 16/3, 2011 at 3:26 Comment(6)
That must be C^2, the next progression of C, where you can use boolean as a type. ;p I also see no reason to refactor this to a function (nor is it a good refactoring), but I won't down vote you for it.Sulphonamide
I haven't used C in about 6 years...and a quick wiki lookup shows you're correct. I'll adjust to make it more syntactically correct.Wingfield
@Gopherkhan: So an int (32 bits) is a more reasonable solution than a bool (8 bits)? (using bool would have been perfect, just harassing you for using the .NET-esque version.)Sulphonamide
@Brad, @Wingfield - Technically C99 has a _Bool type (with #define bool _Bool) type but lots of code still uses int anyway.Nettle
@Chris Lutz: You only get #define bool _Bool if you include <stdbool.h>.Prorate
Funny thing. I remembered a bool when I started the answer, but second guessed boolean. then wiki said the following: "The initial standards for the C language (1972) provided no Boolean type; and, to this day, Boolean values are commonly represented by integers (ints) in C programs. The comparison operators ('>', '==', etc.) are defined to return a signed integer (int) result, either zero (for false) or 1 (for true).", and remembering some of my coworker's c++ code, I switched to int. Regardless, I just hoped to show the asker that a multi-case evaluation was possible without extensive ||'s.Wingfield
D
0

No, sorry, you can't; you have to write all the expressions out. For very long lists of numbers to compare to, you could put the numbers in an array, and loop over the list; but you'd have to have a dozen numbers or so before that started to look like a good idea.

Dipnoan answered 16/3, 2011 at 3:18 Comment(1)
Cheers, we're not allowed to use arrays in class yet but thanks for the tip.Parik
S
0

No, you cannot do this in C. Your first code sample is also incorrect. There is an important distinction between assignment (=) and equivalency (==) in C. When you wrote x = 5 in your expression, this will actually compile and evaluate to either 0 or 1 (false or true) before being logically OR'ed with the next part of the expression!

Your second code sample is also valid C, but it does not do what you want it to do. You read the statement as "(x is assigned to 5) or true or true". This is because any non-zero value in C is logically true. Thus, x will contain the value 5, and evaluate to true, making your if condition true. The rest of the expression does not matter since the || operator short-circuits.

Spirituality answered 16/3, 2011 at 3:23 Comment(0)
A
0

One alternate thought: While there's no "shortcut", if you have a lot of numbers it may be easier for code length and typing sanity to put them all into an array and check against the array in a loop. If you have to compare against many numbers more than once, sort them in an array and use binary searching.

For 3 numbers, though, you have to do it the "long" way.

Armelda answered 16/3, 2011 at 3:47 Comment(0)
A
0
int preconditions[] = { 4,5,78 }; // it should be in most likely order
int i = 0;
for(;i<3;++i) {
   if( x == preconditions[i] ) {
      // code here.
   }
}
Abernon answered 16/3, 2011 at 4:9 Comment(0)
U
0

You can do the for loop if it's a long list, how ever that doesn't really handle the logical operators :-...

#include <stdio.h>

int forbiddenList[13] = {5, 4, 78, 34, 23, 56, 4, 7, 6, 4, 33, 2333, 0};
int length = 13;

int main() {

  int mysteryNum;

  printf("type a number: ");
  scanf("%d",&mysteryNum);

  int i;
  for (i = 0; i <= length; i ++)
    {

      int target = forbiddenList[i];

      if (mysteryNum == target)
        {
          printf("You have chosen of the forbidden list!\n");
          printf("YOU SHALL NOT PASS!!\n");
        }
    }
  return 0;
}

er... haven't done c... ever... you should take C++...

Ungracious answered 16/3, 2011 at 4:14 Comment(2)
Why not do a binary search while you're at it?Schechinger
I like the A* search algorithm myself.Ungracious
F
0

The syntax is:

if(condition1 || condition2 || condition3 || ...){
    // Do something
} else {
    // Do something
}

Answer to your question:

if( (x == 5) || (x == 4) || (x == 78) ){
   //do something
} else {
  //do something
}
Facile answered 27/10, 2022 at 5:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.