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]

Re: [PATCH] Fix for short-enums comparison bug


Jeffrey A Law writes:
 >   > Here's a very simple example which illustrates the bug in question:
 >   > 
 >   > typedef enum {A=0, B, C, D} T;
 >   > main(){
 >   >   T x;
 >   >   for (x=A; x<=D; ++x)
 >   >     printf("%d ", (int)x);
 >   >   putchar('\n');
 >   > }
 >   > 
 >   > If you compile this with no compiler flags set and run it will print 
 >   > 
 >   > 0 1 2 3  
 >   > 
 >   > as expected.  If you compile with -fshort-enums it will loop
 >   > indefinitely, printing all values from 0-255 over and over.

 > I don't have an ANSI C standard here, nor do I have a copy of the ISO C9X
 > standard.  Can someone who does dig into them and determine what happens for
 > an assignment out of the range of an enumerated type and what assumptions
 > the compiler can/can not make about the values an enumerated variable
 > can have?

c89 and c9x say that enumerations have to act like some other integer type.
Which integer type is implementation defined, and can vary from enumeration
to enumeration, but it has to be capable of representing all the values
in the enumeration.

It looks like GCC is choosing unsigned char for this particular enum
with -fshort-enums, which is ok standard-wise.  Given this though,
I don't see why this example shouldn't work the same as it does without
-fshort-enums.


 >   > Try running this with and without the -fshort-enums flag.  If the
 >   > intent of -fshort-enums is to really restrict the value of an
 >   > enumerated type to lie within the min and max of that type, a warning
 >   > should be produced when we set x equal to 10.  But no such warning is
 >   > produced, just bizarre results (the program prints 10<=3 if
 >   > -fshort-enums is used).
 > Actually, whether or not a warning must be produced is a standards issue.  Even
 > if the standards don't demand it, a warning would be nice.  Someone would have
 > to grovel around the front-end though to produce the warning.  Once we've
 > left the language front end it's too late.

IMO, the intent of -fshort-enums is only to have the compiler choose
a smaller integral type for the representation of an enum, and not to 
change the kinds of diagnostics produced.  Warnings about creating
enum values outside the range of the enum, and/or outside the range
of the representation of the enum should be a separate option.  One
or both of these options may already exist in gcc, but I don't know
without looking.


                                           -gavin...



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