are enums integers in ANSI?

dmr at alice.UUCP dmr at alice.UUCP
Sat Nov 26 18:17:13 AEST 1988


Enumeration constants are integer constants, and moreover must
have a value that is representable in type int.  

As Henry said, enum variables turn into ints in all expression
usages and may be freely assigned, passed, and have arithmetic
done on them without casts (see section 3.2.1.1).  I think even the
comments that used to appear in the Draft, saying that the compiler
might warn about mixing one enum type with another, are now gone.

However, enum types are not identical to other types; each enum
constitutes a distinct type (3.1.2.5).  On the other hand, each
enum type is compatible with some integral type (3.5.2.2) though
which one is implementation-defined.

"Compatible with" for types is an interesting (and complicated)
concept in ANSI C.  It is not an equivalence relationship because
it fails to be transitive.  It is used mainly to determine
when two declarations for the same name in a scope are
legal and refer to the same thing.  You can say

	int x[];
	int x[10];

because the types "incomplete array of int" and "array of 10 ints"
are compatible.

How does this relate to enums?  Well, for one thing, it is
never legal to declare

	struct s { enum e x:10; };

because, although enum e is compatible with some integral type,
it is not identical, and the type of a bitfield must be
(signed|unsigned) int. Thus, no enum bitfields.

Here is a more subtle example.

	int x;
	enum e x;

A compiler is permitted to accept this if, for example, it decides
that the integral type all enums are compatible with is int.

It is permitted to reject it also; in fact it may reject it even
if you try all the possibilities of char, unsigned, long, etc. instead
of int.  The reasoning (theoretically) is that the compiler doesn't
have to announce in advance just which variety of int is compatible
with a particular enum.  In effect, it is allowed to play the hostile
adversary, and choose a compatible integral type for this enum other than
the one you guessed!

			Dennis Ritchie
			dmr at research.att.com
			research!dmr



More information about the Comp.std.c mailing list