macro for enum operations

Michael Matz matz at kde.org
Thu Sep 11 13:23:31 BST 2003


Hi,

On Thu, 11 Sep 2003, Lubos Lunak wrote:

> This looks confusing (especially the 0,1,2 vs 0,1,2,3). Are you trying to say

That values of an enumeration not only include those of the enumerators,
but also all values representable by the minimum size bitfield able to
hold all enumerator values.

> enum Values { V0 = 0, V1 = 1, V3 = 3 };
> Values value;
> value = static_cast< Value >( 2 ); // a)
> value = static_cast< Value >( 4 ); // b)

a) is okay, b) is not.   The smallest bitfield able to hold {0,1,3} (your
enumerators) has two bits.  "2" is representable by that, hence is a valid
value for that enum, but "4" is not.

> > If he uses long it's only unsafe for enums which require long long, and
> > those are seldom ;-)
>
> The macros could of course use unsigned long long, if needed. We require
> long long anyway if I'm not mistaken.

We do.  The question is, if it's worthwhile.

>
> [snip]
> > > I am particularly concerned about the "~"  operator because the return
> > > value needs to be converted to EnumType again and I wonder whether
> > > truncation would cause problems with 1s complement vs 2s complement.
> >
> > ~ is indeed conceptually a problem.  Not because of 1s vs 2s complement,
> > but because of the backcast.  Given this:
> >
> > enum E {a,b,c};
> > long l = ~(long)a;
> > enum E e = (enum E)l;
> >
> > the problem arises because l has the value -1L.  This is outside the
> > values of enum E, and hence the resulting enumeration value is
> > unfortunately unspecified.  It could be truncated, or anded, or the
> > machine could explode.  The problem of course is, that without the
> > operator ~, the others make much less sense.  For instance it's possible
> > to set some bit by |, but it's impossible to remove it again (by & and ~).
> > Choose your poison.
>
> Would this be a problem even when using unsigned long instead of long?

In that case 'l' would have value (unsigned long)-1L (i.e. all bits set),
which _also_ lies outside the values of enum E.

> Perhaps that could be fixed by passing bitmask of valid bits to the
> macro.


Ciao,
Michael.





More information about the kde-core-devel mailing list