C ++ how trailing comma is not an error and what happens? Foo x, y ;;
Someone pointed out to me that I had what looks like a typo in some C ++ code:
protected:
Foo x, y,;
I would have thought that the trailing comma would be an error, but apparently it isn't? Is it undefined, or what's going on? Presumably something bad, as the code checker complained about it.
source to share
The corresponding grammatical setting is given in ยง9.2:
member-declarator-list:
member-declarator
member-declarator-list , member-declarator
A comma is allowed to separate declarators (names). the declarator member cannot contain a comma.
EDIT: here is member-declarator ... it's not quite as standalone, the syntax for declarators is generally a spider web.
member-declarator:
declarator virt-specifier-seq(opt) pure-specifier(opt)
declarator brace-or-equal-initializer(opt)
identifier(opt) attribute-specifier-seq(opt) : constant-expression
Incorrect grammar is not undefined behavior; the compiler allowing misplaced commas has a bug. Waiver of this kind of requirement is a requirement of the standard.
Note. Trailing commas are allowed in enumeration definitions and curly brace initializers. I think both cases were added by C ++ 11 to make it easier to write source code generators. (The preprocessor that gets this job most often has a tough time even with such simple requirements.) Typically, a simple generator can avoid creating multiple-named declarations because it might be a worm due to the complex grammar. On the other hand, an empty declaration consisting of ;
, like a semicolon after the definition of a member function is allowed .
source to share