2

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?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
march_seven
  • 691
  • 1
  • 7
  • 13
  • Clearly it is. This is a useful feature for programmers that write the enum members on a multiple lines (usually with a comment) and then, later, delete the last member. – Hans Passant Aug 04 '18 at 16:05
  • Note that in C90, the trailing comma was not allowed. C99 and later has an explicit rule that allows the trailing comma: _`enum identifieropt { enumerator-list , }`_ (the previous alternative in the grammar doesn't have that comma). – Jonathan Leffler Aug 04 '18 at 16:21
  • @HansPassant It's even more convenient for automated generation of enumerated constants. The code generator can simply emit a trailing comma in all cases without having to consider if it's the last one. – Andrew Henle Aug 04 '18 at 16:22

2 Answers2

4
  • No, you don't need the last comma.
  • Yes, it is allowed to have an extra comma at the end.

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.

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
4

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
};
chqrlie
  • 131,814
  • 10
  • 121
  • 189