Reputation: 1173
I want to apply if
statement to check a condition with multiple values, which I know should be something like this:
if (value == 1 || value == 2 || value == 3 || value == 4)
//Do something;
But this does not look good, isn't there any way to check like:
if(value == 1 || 2 || 3 || 4)
Note: I am not trying something in range like:
if (1 <= value && value <= 4)
Upvotes: 2
Views: 6419
Reputation: 1049
Well, I had the same issue and this is the solution I came up.
I created an array, with the values I want to check, and then I use the native array includes()
method to check if the variable value exists on the array. Like this:
[1, 2, 3, 4].includes(value);
If the variable value exists on the array the includes()
method will return a boolean with the value true
. Otherwise it will return a boolean with the value false
.
Upvotes: 0
Reputation: 169
No you cannot write the way you have described. You still have option of switch case and ternary operators. If you want to make it fancy you still have option like
vector<int> v = {1,2,3,4,5}; // desirable values
auto it = find(v.begin(), v.end(), value);
if(it != v.end()){
cout<<"value is equal to something!\n";
// if you want to check which value does it match to
cout<<"Matching value is at index "<<it-v.begin()<<"\n";
}else {
cout<<"Value is not equal to any number!\n";
}
For this you will need to include vector library by using #include <vector>
Upvotes: 1
Reputation: 1637
In case the range of possible values is smaller than the number of bits you can do something like this:
int value = 2;
auto values = {1,2,3,4};
int test = 0;
for(auto i : values)
test |= (1 << i);
if((1 << value) & test)
std::cout << "true" << std::endl;
If you have direct control over the possible values you can also directly set them as bitflags and skip the bitshift part.
Otherwise there is also the option of inverting the condition in case there are fewer possible values that should evaluate to false.
Also you could just loop over an array of valid values and see if any of them matches.
Upvotes: 1
Reputation: 23802
A possible simple alternative would be:
switch (value) { case 1: case 2: case 3: case 4: std::cout << "true"; }
Wether it looks better or not is a matter of taste.
Another alternative would be:
switch (value) { case 1 ... 4: std::cout << "true"; }
But this is not standard C++, I believe it's a GNU extension.
Upvotes: 2
Reputation: 21
No you can not write it as : if(value==1 || 2 || 3 || 4)
You can use conditional statement for different conditions.
Upvotes: 1