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.
If the first value of the enum variable is not initialized then the C compiler automatically assigns the value 0.The compiler keeps on increasing the value of preceeding enum variable by 1.
Eg:
enum months{jan,feb,mar}
Explanation:Value of jan will be 0,feb will be 1,mar will be 2.
enum months{jan=123,feb=999,mar}
Explanation:Value of jan will be 123,feb will be 999,mar will be 1000.
enum months{jan='a',feb='s',mar}
Explanation:Value of jan will be 'a',feb will be 's',mar will be 't'.