Is the sizeof(enum) == sizeof(int), always?

It is compiler dependent and may differ between enums. The following are the semantics

enum X { A, B };

// A has type int
assert(sizeof(A) == sizeof(int));

// some integer type. Maybe even int. This is
// implementation defined. 
assert(sizeof(enum X) == sizeof(some_integer_type));

Note that “some integer type” in C99 may also include extended integer types (which the implementation, however, has to document, if it provides them). The type of the enumeration is some type that can store the value of any enumerator (A and B in this case).

I don’t think there are any penalties in using enumerations. Enumerators are integral constant expressions too (so you may use it to initialize static or file scope variables, for example), and i prefer them to macros whenever possible.

Enumerators don’t need any runtime memory. Only when you create a variable of the enumeration type, you may use runtime memory. Just think of enumerators as compile time constants.

I would just use a type that can store the enumerator values (i should know the rough range of values before-hand), cast to it, and send it over the network. Preferably the type should be some fixed-width one, like int32_t, so it doesn’t come to conflicts when different machines are involved. Or i would print the number, and scan it on the other side, which gets rid of some of these problems.


Response to Edit

Well, the compiler is not required to use any size. An easy thing to see is that the sign of the values matter – unsigned types can have significant performance boost in some calculations. The following is the behavior of GCC 4.4.0 on my box

int main(void) {
  enum X { A = 0 };
  enum X a; // X compatible with "unsigned int"
  unsigned int *p = &a;
}

But if you assign a -1, then GCC choses to use int as the type that X is compatible with

int main(void) {
  enum X { A = -1 };
  enum X a; // X compatible with "int"
  int *p = &a;
}

Using the option --short-enums of GCC, that makes it use the smallest type still fitting all the values.

int main() {
  enum X { A = 0 };
  enum X a; // X compatible with "unsigned char"
  unsigned char *p = &a;
}

In recent versions of GCC, the compiler flag has changed to -fshort-enums. On some targets, the default type is unsigned int. You can check the answer here.

Leave a Comment