Maybe I am not from this planet, but it would seem to me that the following should be a syntax error:
int a[] = {1,2,}; //extra comma in the end
But it's not. I was surprised when this code compiled on Visual Studio, but I have learnt not to trust MSVC compiler as far as C++ rules are concerned, so I checked the standard and it is allowed by the standard as well. You can see 8.5.1 for the grammar rules if you don't believe me.
Why is this allowed? This may be a stupid useless question but I want you to understand why I am asking. If it were a sub-case of a general grammar rule, I would understand - they decided not to make the general grammar any more difficult just to disallow a redundant comma at the end of an initializer list. But no, the additional comma is explicitly allowed. For example, it isn't allowed to have a redundant comma in the end of a function-call argument list (when the function takes ...
), which is normal.
So, again, is there any particular reason this redundant comma is explicitly allowed?
;
when it's clear next token is actually a next statement. – Contritionfor()
for instance), adding it throws a compiler warning. – Gaberonesfor()
is not "ambiguous" at all. – Gyrusif (x = 1)
is not ambiguous in the grammar, but it is very ambiguous to humans, and thus throws a warning. – Gaberonesfor (a; b; c);
means. There is no ambiguity here, neither for the compiler nor for the programmer. That it's often a mistake and easy to miss is pertinent. – Gyrusif
example is not ambiguous either. I don't think "ambiguous" means what you think it means! – Gyrus