# Thread: Question About Or Statements

1. ## Question About Or Statements

Hi,

I have a couple of questions, if anyone wouldn't mind answering them.

1. If you compile the following program, a is recognised by the first if condition, but not the second. Can anyone explain why this is? It seems like in the second condition, (12 || 17 || 31 || 44) should just equate to either 1 or 0 like the first condition.

2. If you can't use something like the second if statement, is there a more efficient way to check whether a variable is one of several different values than via something like the first one?

Thanks.

Code:
```#include <iostream>
using namespace std;

int main()
{
int a = 12;
if ((a == 12) || (a == 17) || (a == 31) || (a == 44))
cout << "a recognised by condition 1" << endl;
if (a == (12 || 17 || 31 || 44))
cout << "a recognised by condition 2" << endl;
}```

2. Well, you said the reason. 12||17||31||44 is, in fact 1 (since 12 is true, and 17 is true, and 31 is true, and 44 is true, and true or true is true, and true is 1 -- || will always return either 0 or 1). a==1 is false, because a is in fact 12.

3. Originally Posted by bengreenwood
1. If you compile the following program, a is recognised by the first if condition, but not the second. Can anyone explain why this is? It seems like in the second condition, (12 || 17 || 31 || 44) should just equate to either 1 or 0 like the first condition.
The expression (12 || 17 || 31 || 44) evaluates to true, but true is converted to 1, and 12 is not equal to 1.

Originally Posted by bengreenwood
2. If you can't use something like the second if statement, is there a more efficient way to check whether a variable is one of several different values than via something like the first one?
The first if statement seems pretty efficient for what you want to do. Depending on the situation you may be able to check if the value lies within a range, e.g., (a >= 12 && a <= 44). Or maybe you can have a std::set of possible values and then attempt to find if the given value is within the set.

EDIT:
Originally Posted by tabstop
|| will always return either 0 or 1
Strictly speaking, the type of the result of the built-in operator|| is a bool. What happens here is an integral promotion from bool to int.

4. Originally Posted by bengreenwood
2. If you can't use something like the second if statement, is there a more efficient way to check whether a variable is one of several different values than via something like the first one?
Yes, yes there is. However it only works on a limited range of values. E.g. for a 32-bit int we can test for any and all values up to 31...
Code:
`if ((1 << a) & ((1<<12) | (1<<17) | (1<<31)))`
You could include the 44 if you do the same thing with 64 bit values.
I never said it was pretty, but hot-dam it's fast!

Popular pages Recent additions