How do I list an enumeration?

Usually, when I create an enumeration, each of them gets an increment of one, see

enum
{
    A = 0,
    B,
    C,
    D
};

but after I looked through some source codes, I see that people do things like this.

enum
{
    A = 0,
    B = 1 << 0,
    C = 1 << 1,
    D = 1 << 2
};

I understand what this means, but what exactly does this give me? Are there any advantages? I only see that this, in my opinion, looks awkward.

+4
source share
2 answers

The second form creates flags for use in the bitmask. This is usually done to save space in objects that have several Boolean conditions that control their behavior.

struct foo {
    std::uint32_t bitmask; // up to 32 different flags.
};

foo obj;
obj.bitmask = (B | D); // Sets the bits 0 and 2 
+7
source

, B | C , D.

, , . = 0 . .

+5

Source: https://habr.com/ru/post/1664089/


All Articles