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

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.)

36
задан aschepler 10 January 2011 в 17:11
поделиться