I have code like this in C:
if (count == 5 || count == 8 || count == 9 || count == 10)
{
// Do something
}
Is there a possibility to write this shorter? Something like:
if (count == 5, 8, 9, 10)
{
// Do something
}
In some cases, it can make sense to use a bit map.
For example, your test:
if (count == 5 || count == 8 || count == 9 || count == 10)
is equivalent to:
if ((1<<count) & 0x720)
The values 5, 8, 9, and 10 are encoded in the bits of the value 0x720.
Typically this would make sense if you have meaningful symbolic constants for the values 5, 8, 9, and 10, with 0x720 constructed from a bitwise "or" (|) of those constants -- which would result in more verbose code than the simple if you have in your question.
In practice, real-world code should minimize the use of "magic numbers". It's difficult to tell what the values 5, 8, 9, and 10 mean.
Possibly you should consider using a different algorithm, but it's impossible to tell without more information.
count < 31 ! (or whatever your int size is)Depending on how many different values and different branches you have it can sometimes be neater/easier to use a switch:
switch (count)
{
case 5:
case 8:
case 9:
case 10:
do_something();
break;
default:
do_something_else();
break;
}
There is no way to insert a comma-separated list into an if statement itself as in your example, but you may write something like this to use the comma-separated list format.
int allowed_counts[] = {5, 8, 9, 10};
int i;
for (i = 0; i < 4; i++) {
if (count == allowed_counts[i]) {
...
break;
}
}
Although, a switch statement is more computationally efficient for all list sizes.
if statement in your question might be the best way to do it. It's more readable than most of the alternatives, and for something this small performance isn't likely to be a significant issue.I think you're looking for something like this:
So the condition is testing if count is 5, 8, 9, 10:
if (count == 5 || (count >= 8 && count <= 10 ))
printf("count is 5, 8, 9 or 10");
count equals 6 or 7!count == 6. The code in the question tests for count equal to 5, 8, 9, or 10, not for a range.count is 4,6,8 or 11? You mean in the condition that the same should happen like if count is 5?)E.g EXIST(count, (5,8,9,10) expand by macro of boost
#include <boost/preprocessor/tuple/to_seq.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <stdio.h>
#define F(r, data, i, elem) BOOST_PP_IF(i, ||, ) (data == elem)
#define EXIST(var, values) BOOST_PP_SEQ_FOR_EACH_I(F, var , BOOST_PP_TUPLE_TO_SEQ(values) )
int main(){
int count;
scanf("%d", &count);
if(EXIST(count, (5,8,9,10)))//if( (count == 5) || (count == 8) || (count == 9) || (count == 10) )
printf("yes\n");
else
printf("no\n");
return 0;
}