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

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

I currently have an if statement that checks if x is equal to 5 or 4 or 78:

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

And I was wondering if I could just condense all of this:

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

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

+3
source share
11 answers

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

if ((x == 5) || (x == 4) || (x == 78)) {
+8
source

-, , ifs. ( ) - , , , . , , , true, 4, 78 true, , , , 5 ( 5 ) 4 78 . switch .

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

, ==, =

+2

if, :

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

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

@uncle brad , , , -, switch. , ( ):

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

switch, if - , .

+1

, , ; . , , ; , .

0

, C. . (=) (==) C. x = 5 , 0, 1 (false true), OR'ed !

C, , . "(x 5) true true". , C . , x 5 true, if . , ||.

0

, ,

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

, , int .

, , , , - , .

0

: "", , , . , .

For three numbers, you have to do it in a "long" way.

0
source
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.
   }
}
0
source

You can make a for loop if it's a long list, as if it weren't processing 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 ... did not c ... ever ... you have to take c ++ ...

0
source

All Articles