standards question relating to uninitialized variables
Joe Buck
jbuck@Synopsys.COM
Wed Mar 31 23:46:00 GMT 1999
> Given this code:
>
> extern void use(int);
>
> enum foo
> {
> a = 0, b, c, d
> };
>
> void
> func(enum foo bar)
> {
> int x;
>
> if(bar == a)
> x = 0;
> else if(bar == b)
> x = 4;
> else if(bar == c)
> x = 9;
> else if(bar == d)
> x = 16;
>
> use(x);
> }
>
> Is GCC allowed to assume that `bar' has one of the defined enumeration
> values when compiling C? What about C++?
For C++, the valid values of an enumeration are the valid values of the
smallest bitfield that can hold all the values of that enumeration.
In this case, that would appear to mean that the compiler can assume
that x is defined before use (but only because the number of values
in the enum is a power of two). Note that C++ blesses the common use
of enums as bitmasks that are anded and ored together, hence the smallest
bitfield rule.
If we want to make egcs C++ more pedantic, we could issue warnings about
foo fred = (foo)5;
as this assigns an out-of-range value to the enum.
However, sizeof(fred) has to be at least 1 (for purposes of packing into
structs).
For C, it seems that an enum is just an int with a bit of syntactic sugar,
so it wouldn't seem that the assumption is safe.
More information about the Gcc
mailing list