C & C++

C & C++

Made by DeepSource

Misuse of enum as an improper bitmask CXX-W2056

Bug risk
Major

Using enum as a bitmask or flags is only valid if the members are only assigned values in the power of twos.

Consider using enums as bitmasks only when the enum elements have values that are powers of 2. This ensures that each element represents a distinct bit in the bitmask. If the elements have non-power-of-2 values, it is recommended to use a different approach.

Bad Practice

enum Bitmask {
  A = 0,
  B = 1,
  C = 2,
  D = 4,
  E = 8,
  F = 16,
  G = 31 // OK, real bitmask.
};

enum Almostbitmask {
  AA = 0,
  BB = 1,
  CC = 2,
  DD = 4,
  EE = 8,
  FF = 16,
  GG // Problem, forgot to initialize.
};

unsigned flag = 0;
flag |= E; // OK.
flag |= EE; // Warning at the decl, and note that it was used here as a bitmask.

Recommended

enum Bitmask {
  A = 0,
  B = 1,
  C = 2,
  D = 4,
  E = 8,
  F = 16,
  G = 31 // OK, real bitmask.
};

enum Almostbitmask {
  AA = 0,
  BB = 1,
  CC = 2,
  DD = 4,
  EE = 8,
  FF = 16,
  GG = 31 // Fixed.
};

unsigned flag = 0;
flag |= E; // OK.
flag |= EE; // Fine now.

References