Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading