if (mask & VALUE) or if ((mask & VALUE) == VALUE)?

aschepler picture aschepler · Jan 10, 2011 · Viewed 28.2k times · Source

You're probably familiar with the enum bitmask scheme, like:

enum Flags {
    FLAG1 = 0x1,
    FLAG2 = 0x2,
    FLAG3 = 0x4,
    FLAG4 = 0x8,

    NO_FLAGS = 0,
    ALL_FLAGS = FLAG1 | FLAG2 | FLAG3 | FLAG4
};

f(FLAG2 | FLAG4);

I've seen a lot of code that then tests for a certain bit in the mask like

if ((mask & FLAG3) == FLAG3)

But isn't that equivalent to this?

if (mask & FLAG3)

Is there some reason to use the first version? In my opinion, the second shorter version is more legible.

Maybe leftover habits from C programmers who think true values should be converted to 1? (Though even there, the longer version makes more sense in an assignment or return statement than in a conditional statement test.)

Answer

David Gelhar picture David Gelhar · Jan 10, 2011

The construct if ((mask & FLAG3) == FLAG3) tests if all bits in FLAG3 are present in mask; if (mask & FLAG3) tests if any are present.

If you know FLAG3 has exactly 1 bit set, they are equivalent, but if you are potentially defining compound conditions, it can be clearer to get into the habit of explicitly testing for all bits, if that's what you mean.