Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does this C++ casting to enum have problems?

Tags:

c++

enums

casting

Given the following code:

enum Options
{
    Surf     = 0x01,
    Out      = 0x02
};

Options all = (Options) ( Surf | Out);
  1. Does this casting have problems?
  2. If this casting make sense, then why?

Based on my understanding, Options only defines two variables. How does the value 0x03 makes sense?

like image 643
q0987 Avatar asked Feb 26 '23 09:02

q0987


1 Answers

Does this casting have problems?

No.

If this casting make sense, then why? Based on my understanding, Options only defines two variables, how the value 0x03 makes sense?

The enumeration type Options has two named enumerators, but the range of values that it represents is large enough that it can be used as a bitfield containing each of the enumerators.

In short: yes, it is valid and well-defined to use an enumeration for a bitfield like this.

As requested in the comments to this answer, the formal language permitting this can be found in the C++ Standard (C++03 7.2/6):

For an enumeration where emin is the smallest enumerator and emax is the largest, the values of the enumeration are the values of the underlying type in the range bmin to bmax, where bmin and bmax are, respectively, the smallest and largest values of the smallest bit-field that can store emin and emax.

It is possible to define an enumeration that has values not defined by any of its enumerators.

There is some debate as to whether or not this is good style. Certainly it can be argued that it is often assumed that an enumeration object can only store one of its enumerators, so code like this could be confusing and error-prone.

On the other hand, I would argue that it is usually quite obvious when an enumeration is intended for use as a bitfield. Usually such an enumeration is named with an Options or Flags suffix or something similar. Likewise, if each of the enumerators has a set value that is clearly a single set bit, that enumeration is probably intended for use as a bitfield.

like image 134
James McNellis Avatar answered Mar 08 '23 08:03

James McNellis