Lehane Lehane - 1 year ago 100
C Question

Is the last comma in C enum required?

Is the last comma required in a C enum declaration?

i.e. is the comma after VAL3 required?

enum{Val1, Val2, Val3,} someEnum;

Are there any side-effects of leaving it in/out


Answer Source

It's not required. Section of C99 lists the syntax as:

    enum identifieropt { enumerator-list }
    enum identifieropt { enumerator-list , }
    enum identifier
    enumerator-list , enumerator
    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 {
} 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.

And, as pointed out in a comment, 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download