PeterK
PeterK

Reputation: 6317

Is using enum for integer bit oriented operations in C++ reliable/safe?

Consider the following (simplified) code:

enum eTestMode
{
    TM_BASIC        = 1,    // 1 << 0
    TM_ADV_1        = 1 << 1,
    TM_ADV_2        = 1 << 2
};

...

int m_iTestMode;    // a "bit field"

bool isSet( eTestMode tsm )
{ 
    return ( (m_iTestMode & tsm) == tsm );
}

void setTestMode( eTestMode tsm )
{
    m_iTestMode |= tsm;
}

Is this reliable, safe and/or good practice? Or is there a better way of achieving what i want to do apart from using const ints instead of enum? I would really prefer enums, but code reliability is more important than readability.

Upvotes: 4

Views: 596

Answers (4)

AnT stands with Russia
AnT stands with Russia

Reputation: 320451

Using enums for representing bit patterns, masks and flags is not always a good idea because enums generally promote to signed integer type, while for bit-based operation unsigned types are almost always preferable.

Upvotes: 0

rwong
rwong

Reputation: 6162

See also What is the size of an enum in C?

For some compilers (e.g. VC++) this non-standard width specifier can be used:

enum eTestMode : unsigned __int32
{ 
    TM_BASIC        = 1,    // 1 << 0 
    TM_ADV_1        = 1 << 1, 
    TM_ADV_2        = 1 << 2 
}; 

Upvotes: 0

ereOn
ereOn

Reputation: 55736

I can't see anything bad in that design.

However, keep in mind that enum types can hold unspecified values. Depending on who uses your functions, you might want to check first that the value of tsm is a valid enumeration value.

Since enums are integer values, one could do something like:

eTestMode tsm = static_cast<eTestMode>(17); // We consider here that 17 is not a valid value for your enumeration.

However, doing this is ugly and you might just consider that doing so results in undefined behavior.

Upvotes: 5

AProgrammer
AProgrammer

Reputation: 52284

There is no problem. You can even use an variable of eTestMode (and defines bit manipulation for that type) as it is guaranteed to hold all possible values in that case.

Upvotes: 0

Related Questions