Are default enum values in C the same for all compilers?
C99 Standard
The N1265 C99 draft says at 6.7.2.2/3 "Enumeration specifiers"
An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no
=
, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant. (The use of enumerators with = may produce enumeration constants with values that duplicate other values in the same enumeration.)
So the following always holds on conforming implementations:
main.c
#include <assert.h>
#include <limits.h>
enum E {
E0,
E1,
E2 = 3,
E3 = 3,
E4,
E5 = INT_MAX,
#if 0
/* error: overflow in enumeration values */
E6,
#endif
};
int main(void) {
/* If unspecified, the first is 0. */
assert(E0 == 0);
assert(E1 == 1);
/* Repeated number, no problem. */
assert(E2 == 3);
assert(E3 == 3);
/* Continue from the last one. */
assert(E4 == 4);
assert(E5 == INT_MAX);
return 0;
}
Compile and run:
gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Tested in Ubuntu 16.04, GCC 6.4.0.
Yes. Unless you specify otherwise in the definition of the enumeration, the initial enumerator always has the value zero and the value of each subsequent enumerator is one greater than the previous enumerator.