0

Given an enumeration defined like so:

enum DebugModeType { DebugModeNone = 0, DebugModeButton = 1, DebugModeFPS = 2, DebugModeData = 4 }; #define DebugMode DebugModeButton|DebugModeData 

I expect the value of DebugMode&DebugModeFPS to be 0, but I observe it to be 1.

1 Answer 1

4

You need parentheses in your macro to overcome operator precedence:

#define DebugMode (DebugModeButton|DebugModeData) 

As-is:

DebugMode & DebugModeFPS

= DebugModeButton | DebugModeData & DebugModeFPS

(which is parsed as DebugModeButton | (DebugModeData & DebugModeFPS))

= DebugModeButton | (4 & 2)

= DebugModeButton | 0

= DebugModeButton

= 1

With parentheses as I suggest:

= (DebugModeButton | DebugModeData) & DebugModeFPS

= 5 & DebugModeFPS

= 5 & 2

= 0

Sign up to request clarification or add additional context in comments.

4 Comments

nice nice. #define DebugMode (DebugModeButton|DebugModeData) or #define DebugMode DebugModeButton+DebugModeData also works well. Give it a high priority. Thank you very much.
Better yet, don't use macros, use constants, and avoid this any many other macro pitfalls.
@zszen I recommend against using + operator because if you have some bit flags already set you will end up unsetting it and setting some other flag unintentionally.
@Richard . Thx, I now usally use bit operator instead + operator

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.