Is the last comma in C enum required?
In standard C89, the last comma is not permitted. Full stop.
It was a common extension to allow it; in particular, it was supported by GCC, but the standard expressly disallowed it.
In standard C99, the last comma is allowed, for symmetry with array and structure initializers, which always did allow the trailing comma on the last item.
6.7.2.2 Enumeration specifiers
Syntax
enum-specifier: enum identifieropt { enumerator-list } enum identifieropt { enumerator-list , } enum identifier
The primary advantage of permitting trailing commas is that it permits easier machine generation of (C source) code - you do not have to write special case code for the last (or, maybe, the first) item in the list of initializers. Hence, programs like Yacc and Lex, to name but two, can be slightly simpler.
Like everyone else says, the comma is not required. But it's new in C99 (wasn't allowed in C89) and will be allowed in the next version of C++ too.
One other rationale is to make a difference between a "length" enumerator and a normal enumerator:
enum Items {
A,
B,
C,
LENGTH
};
Now, you can put into your coding guideline that the last item in your enumeration should have a comma applied, but not if it is a "Length" item - which just tells how many items there are.
It also helps for automatic generation of items (using macros/preprocessors) like other answers explain.
It's not required. Section 6.7.2.2
of C99 lists the syntax as:
enum-specifier:
enum identifieropt { enumerator-list }
enum identifieropt { enumerator-list , }
enum identifier
enumerator-list:
enumerator
enumerator-list , enumerator
enumerator:
enumeration-constant
enumeration-constant = constant-expression
Notice the first two forms of enum-specifier
, one with the trailing comma and one without.
One advantage I've seen to using it is in things like:
enum {
Val1,
Val2,
Val3,
} someEnum;
where, if you want to add in (for example) Val4
and Val5
, you just copy and paste the Val3
line without having to worry about adjusting commas.
It can also be to simplify automated code generators so that they don't have to have special handling for the final value. They can just output every value followed by a comma.
This can be likened to the oft-seen SQL:
select fld1, fld2 from tbl where 1=1 and fld1 > 8
In that case, the where 1=1
is there only so that you don't have to put a where
before your first clause and an and
before each subsequent one. You can just rely on the fact that the where
is already there and just use and
for all the ones you add.
Some people may think this reeks of laziness and they're right, but that's not necessarily a bad thing :-)
Any decent DBMS query optimiser should be able to strip out constant clause like that before going to the database tables.