Search code examples
cenumsbitwise-operatorsbit-shift

Why use the Bitwise-Shift operator for values in a C enum definition?


Apple sometimes uses the Bitwise-Shift operator in their enum definitions. For example, in the CGDirectDisplay.h file which is part of Core Graphics:

enum {
  kCGDisplayBeginConfigurationFlag  = (1 << 0),
  kCGDisplayMovedFlag           = (1 << 1),
  kCGDisplaySetMainFlag         = (1 << 2),
  kCGDisplaySetModeFlag         = (1 << 3),
  kCGDisplayAddFlag         = (1 << 4),
  kCGDisplayRemoveFlag          = (1 << 5),
  kCGDisplayEnabledFlag         = (1 << 8),
  kCGDisplayDisabledFlag        = (1 << 9),
  kCGDisplayMirrorFlag          = (1 << 10),
  kCGDisplayUnMirrorFlag        = (1 << 11),
  kCGDisplayDesktopShapeChangedFlag = (1 << 12)
};
typedef uint32_t CGDisplayChangeSummaryFlags;

Why not simply use incrementing int's like in a "normal" enum?


Solution

  • This way you can add multiple flags together to create a "set" of flags and can then use & to find out whether any given flag is in such a set.

    You couldn't do that if it simply used incrementing numbers.

    Example:

    int flags = kCGDisplayMovedFlag | kCGDisplaySetMainFlag; // 6
    if(flags & kCGDisplayMovedFlag) {} // true
    if(flags & kCGDisplaySetModeFlag) {} // not true