Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How should I numerate my enum?

Tags:

c++

enums

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.

like image 804
anon Avatar asked Dec 15 '22 01:12

anon


1 Answers

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 
like image 139
StoryTeller - Unslander Monica Avatar answered Dec 16 '22 13:12

StoryTeller - Unslander Monica