0

I have noticed that many functions take parameters or "flags" like so:

foo(BIG | RED | SWEET);

Where BIG, RED, and SWEET have been #define'ed earlier in the file such as: #define BIG 0x1

I want to implement my own functions that take parameters like above but I am worried that ORing two numbers together might equal the same result as ORing two different numbers. What is the proper way to define these variables so there is no collision?

mc110
  • 2,825
  • 5
  • 20
  • 21
user3205087
  • 91
  • 1
  • 1
  • 3

2 Answers2

0

Usually the flags will be powers of 2, ensuring that each combination is unique.

mc110
  • 2,825
  • 5
  • 20
  • 21
0

The following powers of 2 hex pattern is commonly used to avoid collisions with flags:

#define A    (0x0000)
#define B    (0x0001)
#define C    (0x0002)
#define D    (0x0004)
#define E    (0x0008)
#define F    (0x0010)
#define G    (0x0020)
#define H    (0x0040)
#define I    (0x0080)
#define J    (0x0100)
...

Or better yet, use enums:

enum Flags
{
    A = 0,
    B = 1 << 0,
    C = 1 << 1,
    D = 1 << 2,
    E = 1 << 3,
    F = 1 << 4,
    ...
}

This C++ approach far is more pleasing to the eyes than those hex defines

bstar55
  • 3,542
  • 3
  • 20
  • 24