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.

+3


source to share


2 answers


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 .

+6


source


My observations

GCC 4.6.2:

void myFunc()
{
  int x, y, ; // <-- Syntax error
}

      

But

class MyClass
{
  int x, y,; // <-- No error (one extra comma) but last comma is ignored
};

      



MSVC 2008:

Both of them make mistakes

OpenWatcom 1.8:

Both of them make mistakes

+1


source







All Articles