2

is there any way how to check if the variable equals some value faster way than doing if statement ( m == value1 || m == value2 || m == value3...) I tried if m == ( value1 || value2 || ...) but it works only for the first value. Here's an example, it returns true for 1 but not for 5 and the rest. I really appreciate all suggestions. TY!

#include <stdio.h>

int main(void){
    int m;
    scanf("%i", &m);
    if(m == (1 || 5 || 7 ||  8 || 11 || 20)){
    printf("TRUE\n");
    }
    else {
    printf("FALSE\n");
    }

    return 0;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
Kedge
  • 43
  • 1
  • 5

2 Answers2

2

The || operator performs a logical OR between its two operands. It evaluates to 1 if either operand is non-zero. In the case of 1 || 5 This evaluates to 1 because at least one operand is non-zero. This evaluation continues on for each successive || operator.

So the whole expression (1 || 5 || 7 || 8 || 11 || 20) is equal to 1.

Your original check is the proper way to do this. If you want something a bit less repetitive, you could do this with a switch statement with fallthrough cases:

switch (m) {
case 1:
case 5:
case 7:
case 8:
case 11:
case 20:
    printf("true\n");
    break;
default:
    printf("false\n");
    break;
}
dbush
  • 205,898
  • 23
  • 218
  • 273
2

if(m == (1 || 5 || 7 || 8 || 11 || 20)) actually doesn't do what you think it does. First it computes the result of (1 || 5 || 7 || 8 || 11 || 20) which is true (1). Then it compares m to that result. So this only works when m is 1. An easier way to do this is a switch statement:

switch(m) {
case 1:
  // do something
  break; // don't forget this
case 2:
  // do something
  break;
default:
  // do something when it's not any of the numbers you expect
  break;
}

In your case, since you want to do the same thing for all those number, just omit break; between case statements and they will all get executed:

switch(m) {
case 1:
case 2:
  // do something (when it's 1 or 2)
  break;
default:
  // do something when it's not any of the numbers you expect
  break;
}
Kon
  • 4,023
  • 4
  • 24
  • 38