I saw an enum
defined like below:
enum DAY{MON = 1, TUE, WED, THU, FRI, SAT, SUN,};
...and it compiles successfully.
Is adding an extra "," after the last element ok?
I saw an enum
defined like below:
enum DAY{MON = 1, TUE, WED, THU, FRI, SAT, SUN,};
...and it compiles successfully.
Is adding an extra "," after the last element ok?
This declaration:
enum DAY{MON = 1, TUE, WED, THU, FRI, SAT, SUN,};
...is the same as:
enum DAY{MON = 1, TUE, WED, THU, FRI, SAT, SUN};
To understand the advantages of allowing this syntax, check out @chqrlie's answer.
The trailing ,
in an enum
definition or array initializer is optional, but quite useful, especially in lists spanning multiple lines. It is allowed since C99 for reasons of symmetry as it avoids a different syntax for the last item in the list:
enum DAY {
MON = 1,
TUE,
WED,
THU,
FRI,
SAT,
SUN,
};
It makes it easier to generate array contents with scripts and avoids error prone situations where adding extra elements to an array but forgetting to add a comma might go unnoticed:
const char *osnames[] = {
"CP/M",
"MS/DOS",
"Windows"
}
Adding extra items:
const char *osnames[] = {
"CP/M",
"MS/DOS",
"Windows"
"Linux",
"OS/X"
};
Notice the missing comma in the middle of the list: the compiler parses the third string as "WindowsLinux"
and the bug does not generate a syntax error.
With the trailing ,
on each line, it is much easier to add and delete items without modifying other lines. It is even more useful if lines are compiled conditionally as in this example:
const char *osnames[] = {
"CP/M",
"MS/DOS",
"Windows",
#ifdef __UNIX__
"Linux",
"OS/X",
#endif
};