Why do we always declare constants to be powers of 2?

One good reason is bitmasking. As an example, if you are using constants to represent attributes of an object (or anything else), you can save many attributes into a single integer through bitmasking, and identify the individual attributes later. Great for saving many "flags" in a database.


Powers of 2 are convenient because they map well to underlying constraints in hardware.

Such as:

  1. Page size
  2. Address space limits
  3. Alignment constaints (DWORD or QWORD alignment generally, both powers of 2)

For flags, powers of 2 always have a single bit set. So things like MY_FLAG_1 | MY_FLAG_2 | MY_FLAG_3 | ... only work with powers of two. Likewise for testing for flags with &.

Its also something of a convention to pick the nearest larger power of two for buffer sizes and the like.