Home > OS >  How to check two flags at the same time in a single condition
How to check two flags at the same time in a single condition

Time:09-21

I would like to be able to check two flags in a single condition but I can't find the right way to do it.

Here is an example of one of the things I tried:

#include <stdio.h>

#define FLAG_1 0x01
#define FLAG_2 0x02

void check_flags(int flags)
{
    if (flags & FLAG_1)
        printf("Flag 1\n");

    else if (flags & FLAG_2)
        printf("Flag 2\n");

    else if (flags & FLAG_1 | FLAG_2)
        printf("Flag 1 and 2\n");
}

int main(void)
{
    check_flags(FLAG_1 | FLAG_2);

    return 0;
}

CodePudding user response:

You have two problems:

The first problem is your use of if ... else if ... It will be clearer if we reformat the code somewhat:

if (flags & FLAG_1)
{
    printf("Flag 1\n");
}
else
{
    if (flags & FLAG_2)
    {
        printf("Flag 2\n");
    }
    else
    {
        if (flags & FLAG_1 | FLAG_2)
        {
            printf("Flag 1 and 2\n");
        }
    }
}

Because if (flags & FLAG_1) will be true, the code won't check any other condition. You need to change the order of your checks.

The second is because the bitwise AND operator & have higher precedence than bitwise OR |. The expression flags & FLAG_1 | FLAG_2 is really the same as (flags & FLAG_1) | FLAG_2, which will always be "true".

Putting it all together, try something like this:

if (flags & (FLAG_1 | FLAG_2))
    printf("Flag 1 and 2\n");
else if (flags & FLAG_1)
    printf("Flag 1\n");
else if (flags & FLAG_2)
    printf("Flag 2\n");

CodePudding user response:

Try:

(flags & (FLAG_1 | FLAG_2)) == (FLAG_1 | FLAG_2)

Moreover, move this check at the beginning because otherwise it will be dominated by if (flags & FLAG_1) branch.

  •  Tags:  
  • c
  • Related