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

前端 未结 8 1320
眼角桃花
眼角桃花 2020-12-02 10:42

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

8条回答
  •  没有蜡笔的小新
    2020-12-02 10:59

    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
    

提交回复
热议问题