Are default enum values in C the same for all compilers?

CEnums

C Problem Overview


When declaring an enum as shown below, do all C compilers set the default values as x=0, y=1, and z=2 on both Linux and Windows systems?

typedef enum {
    x,
    y,
    z
} someName;

C Solutions


Solution 1 - C

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.

Solution 2 - C

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.

Solution 3 - C

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'.

Solution 4 - C

Yes,enum value bydefult start from 0 to n'th element to any platform.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSSSView Question on Stackoverflow
Solution 1 - CJames McNellisView Answer on Stackoverflow
Solution 2 - CCiro Santilli Путлер Капут 六四事View Answer on Stackoverflow
Solution 3 - CVignesh vickyView Answer on Stackoverflow
Solution 4 - CDevidas GaikwadView Answer on Stackoverflow