The reason for explicitly start C/C++ enum at 0

Viewed 221

I know that and standards state that if you don't specify first element's value a start value of enum will default to 0.
But e.g. in Linux kernel sources I faced strange declarations dozens of times. e.g. numa_faults_stats:

enum numa_faults_stats {
    NUMA_MEM = 0,
    NUMA_CPU,
    NUMA_MEMBUF,
    NUMA_CPUBUF
};

What is the need for explicitly set first element of this enum to 0?

Related post.

2 Answers

There are very many rules for various things in C and C++: this being one of them. Sometimes it's nice to be explicit, for clarity.

Another common one is to use variable names in function prototypes (only the types are needed). Yet another is a return 0; in main in either language. The explicit use of public and private in a C++ class or struct is another.

You can use enums without care its value like only using it comprasions with each other. But sometimes its value is important. You may use is as an index of an array. eg.

 struct NUMA Numa[N];
 Numa[NUMA_MEM];
 Numa[NUMA_CPU];

In this case it is definitly good idea explicitly assing value even it is default equal. You emphasize that its value has usage in code.

Related