anon
anon

Reputation: 210

How should I numerate my enum?

Normally, when I create an enum they each get incremented by one, see

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

but after I looked into some source codes, I see people doing things like this

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

I understand what it means, but what exactly does this grant me? Are there any advantages? I only see that this makes it look unneccesary complex in my opinion.

Upvotes: 4

Views: 141

Answers (2)

Bo Persson
Bo Persson

Reputation: 92271

It creates a bit-mask type with unique bits set, so that the expression B | C is guaranteed not to be the same as D.

If you just want unique enum values that are not combined, the first version is totally ok. And you don't really have to use = 0 for the first value. That will be the default anyway.

Upvotes: 5

The second form creates flags for use in a bitmask. It's normally 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 

Upvotes: 7

Related Questions