Typedef and bit masks

Does it make sense to typedef an enum used for bit masks?
I've seen code where they are typedef'd, but doing so means I'd have to overload bitwise operators for every enum and it's a bit annoying

Is there any advantage in declaring a mask variable with its own type instead of just using an int?
In C++, an enum isn't necessarily an int. It's one of the subtle difference with C.

I'm not sure that that's a suitable use for an enum as you wouldn't naturally think of a mask as a sequence or enumeration.
Last edited on
Well, a mask is a sequence of bits, and it's the same as #defining every value but saves some typing

So the only advantage is that it takes less memory than an int?
closed account (zb0S216C)
maeriden wrote:
"Does it make sense to typedef an enum used for bit masks?"

The use of enumerations is favoured over the use of pre-processor constants. But why would you type-define an enumeration? Wouldn't the initial identifier suffice?

maeriden wrote:
"Is there any advantage in declaring a mask variable with its own type instead of just using an int?"

Yes: any instantiations of an enumeration can only be assigned to enumerators that pertain to the enumeration. For example:

1
2
3
4
5
6
enum LockFlags
{
    LOCK_MATERIAL_STEEL = ( 1 << 0 ),
    LOCK_MATERIAL_IRON = ( 1 << 1 ),
    LOCK_LOCKED = ( 1 << 2 )
} Lock( LOCK_MATERIAL_STEEL | LOCK_LOCKED );

Only the enumerators of LockFlags can be assigned to Lock. If you had an ordinary int, masks could conflict by causing overlapping of the masks. Of course, this is caused by careless programming. If a constant variable/object's value is known at compiler time, the compiler doesn't have to allocate memory for it.

By the way, int isn't always the underlying type of an enumeration, because the type used is implementation defined.

Wazzak
Last edited on
Topic archived. No new replies allowed.