Gugi
Gugi

Reputation: 23

How to combine multiple If conditions in C

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
}

Upvotes: 0

Views: 263

Answers (5)

Paul R
Paul R

Reputation: 212929

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;
}

Upvotes: 4

BLUEPIXY
BLUEPIXY

Reputation: 40145

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;
}

Upvotes: 0

Rizier123
Rizier123

Reputation: 59681

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");

Upvotes: 0

Vortico
Vortico

Reputation: 2749

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.

Upvotes: 3

Keith Thompson
Keith Thompson

Reputation: 263177

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.

Upvotes: 4

Related Questions