bit-level logic operations on enums
Steven Schveighoffer
schveiguy at yahoo.com
Fri Mar 1 11:13:36 PST 2013
On Fri, 01 Mar 2013 07:56:21 -0500, d coder <dlang.coder at gmail.com> wrote:
> Greetings
>
> Currently DMD allows me to bit-or two enum variables, but not bit-and.
> For
> example in the following code, DMD is OK with line 6, but gives an error
> for line 9. I do not see any logic why DMD does that. Is it a bug or is
> it
> intended.
It is a bug that line 6 is not an error:
BING_e c = a | b; // OK (bug!)
writeln(typeof(a | b).stringof); // int
BING_e c2 = 0b11; // ERROR, cannot assign int value to enum BING_e (should
be the message for 2 lines above as well)
D does not (or at least should not) allow assignments of integers back to
enumeration types. You have to cast. Any time an enumeration is involved
in a math operation, it becomes an integer (as my code shows).
The "correct" way to do this is not to store the result of an operation
with flags as an enum, but rather as a uint (or ushort or ubyte). Then
check flags using the enum.
In other words, c and d in your code should be ubytes, not BING_e.
The largest drawback to this approach is that typechecking for enums is
gone when calling functions -- your function has to take a uint, not the
enum, and random bits, other enum bits, etc can be passed in. Of course,
technically, this is possible anyway, and often times certain flag sets
are invalid. Impossible for the compiler to verify these things for you,
you might want to use an in clause for the function to verify the bitset
is correct.
-Steve
More information about the Digitalmars-d
mailing list