Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerator type versus compatible type

According to the draft C11 Standard N1539, an enum in C has the following semantics (edited for brevity)

Semantics

3 The identifiers in an enumerator list are declared as constants that have type int and may appear wherever such are permitted. [...]

4 Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration. [...]

C11 §6.7.2.2 3-4

Questions: if all the individual enumerators are constants of type int, why can the compatible type of the enum as a whole be an implementation-defined type? Why don't the enumerators have the same compatible type?

like image 784
TemplateRex Avatar asked Aug 16 '26 00:08

TemplateRex


1 Answers

Expanding on @Lundin comment, this approach is consistent with C constants like 'A' having type int rather than char.

In C, there really are no raw constants of type smaller than int. C favors promoting smaller types to int when possible. I suspect it made for a simpler compiler - something important in 1970s.

By allowing an instance of enum to be smaller, it takes up less space, much like a char may be smaller than int, as is usual.

int main(void) {
  char ch = 'A';
  enum EN {
    EN_a = 0, EN_b = 1
  };
  enum EN en;

  printf("sizeof (int):%zu\n", sizeof(int));
  printf("sizeof ch   :%zu (1 - by definition)\n", sizeof ch);
  printf("sizeof 'A'  :%zu (same as sizeof (int))\n", sizeof('A'));
  printf("sizeof en   :%zu (implementation defined)\n", sizeof en);
  printf("sizeof EN_a :%zu (same as sizeof (int))\n", sizeof EN_a);
}

Sample output

sizeof (int):4
sizeof ch   :1 (1 - by definition)
sizeof 'A'  :4 (same as sizeof (int))
sizeof en   :4 (implementation defined)
sizeof EN_a :4 (same as sizeof (int))

Not commenting as to is this is a good design - just explaining my understanding of why.

like image 99
chux - Reinstate Monica Avatar answered Aug 18 '26 15:08

chux - Reinstate Monica