JWpark
JWpark

Reputation: 15

How to combine comparisons of the same variable in if statements

if (i != 0 && i != 15 && i != 20)
{
    ...
}

For the above code snippet, how can I combine all the conditions so I won't have to use multiple comparison operators?

Upvotes: -1

Views: 94

Answers (2)

Lundin
Lundin

Reputation: 214770

If you only have 3 checks to perform, the chained && in your original code is probably the most readable and shouldn't be changed. Just keep De Morgan's Laws in mind when negating boolean expressions - getting those wrong is a common bug.

You could use a loop, but that's probably only sensible if you have a whole lot of checks to carry out than just 3:

const int conditions[] = {0, 15, 20};
bool ok= true;

for(size_t i=0; i<sizeof conditions/sizeof *conditions; i++)
{
  if(n==conditions[i])
  {
    ok = false;
    break;
  }
}

if(ok)
{
  ...
}

For values less than 256 you could also perhaps use memchr, though that's also more obscure than what you already have:

#include <string.h>

const unsigned char conditions[] = {0, 15, 20};
if(memchr(conditions, n, sizeof conditions) == NULL)
{
  // n does not equal any of the conditions
}

Upvotes: 0

Dominique
Dominique

Reputation: 17565

In other languages, you might use something like:

if (!(i in (0, 15,20)))
{
    ...
}

But as far as I know, this does not work in C.

So there's no way out of this.

However, I would advise you to use the following formatting:

if (i != 0  && // meaning of  0 value
    i != 15 && // meaning of 15 value
    i != 20)   // meaning of 20 value
{
    ...
}

As you see, putting every single condition on a separate line increases readability and gives you the opportunity to add comments for that one condition. The usage of such comments is seen as a burden by starting programmers, but once you have experienced the burden of needing to re-think a piece of code, multiple months after having developed it, you'll understand the usage of such comments :-)

Upvotes: 1

Related Questions