This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Help with bit-field semantics in C and C++


On Tue, 24 Aug 2004, Joe Buck wrote:
> > I think that the middle end should, at least by default, try to generate
> > the best code possible for conformant programs that use C++ enums.  In
> > most cases, that probably means treating them as belonging to the
> > underlying integer type; the exception would be where the limited range
> > allows for, say, more efficient switch statements, or to determine that
> > some code is unreachable.

On Tue, Aug 24, 2004 at 11:05:41AM -0600, Roger Sayle wrote:
> The problem here is that a C++ enum can hold values outside the range
> of it's type.

If it does, the program is not a valid ISO C++ program.  It is the
equivalent of trying to access memory past the end of an array (though I
cannot promise that the standard uses the same word, e.g. "unspecified" or
"undefined", to describe both of these conditions).

> 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;
> }

The behavior of the above program is unspecified.

> To paraphrase Mike Stump, "undefined" allows us to "rm -rf ~/" or
> core dump, I'm not sure if "unspecified" also allows us to seg fault
> in the case above?

Yes.  But more likely, the implementation might generate code equivalent
to
    if (x == zero) foo(); else bar();

or
    if (x == one) bar(); else foo();

A jump-table implemention would be more likely, say, if the enum has
8 or 16 values.  In such a case, an out-of-range value might cause a jump
to a random address.

> The C++ front-end or gimplifier could insert an "x & 1" into the
> switch condition which would work...

Why?  Should the front end also try to munge pointers so that
the user never gets a segfault?


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]