Help with bit-field semantics in C and C++
Mark Mitchell
mark@codesourcery.com
Tue Aug 24 18:33:00 GMT 2004
Dave Korn wrote:
>>-----Original Message-----
>>From: gcc-owner On Behalf Of Mark Mitchell
>>Sent: 24 August 2004 18:55
>>To: Roger Sayle
>>
>>
>
>
>
>
>>>The problem here is that a C++ enum can hold values outside the range
>>>of it's type.
>>>
>>>enum E { zero = 0x00, one = 0x01 };
>>>
>>>void test(int n)
>>>{
>>> enum E x;
>>>
>>> x = (E)n;
>>> switch (x)
>>> {
>>> case zero: foo(); break;
>>> case one: bar(); break;
>>> }
>>>}
>>>
>>>int main()
>>>{
>>> test(255);
>>> return 0;
>>>}
>>>
>>>
>
>
>
>>What's unspecified is what happens when you convert 255 to E.
>>
>>
>
> Can't we determine by analogy to what happens when you cast 65535 to
>short? IOW, isn't this just the same as any other cast of an out-of-range
>value to a smaller size?
>
>
Yes, from the point of view of the standard.
But, the difference is that short tends to be two whole bytes, and if
you always look at two bytes when dealing with a short, you never get a
value that isn't in the domain of short. Roger's point is that there
are values that fit in the number of bits allcoated to the enum that are
not valid values in the underlying type, which creates some additional
complexity.
Introducing mask operations would greatly penalize the well-specified
case where the only values you ever assign to an enum are ones that are
within its range.
--
Mark Mitchell
CodeSourcery, LLC
(916) 791-8304
mark@codesourcery.com
More information about the Gcc
mailing list