Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
81 views
in Technique[技术] by (71.8m points)

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

question from:https://stackoverflow.com/questions/4649231/if-mask-value-or-if-mask-value-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...