Reputation: 1714
Once upon a time I was writing a C compiler in a computer science course on compilers. Part of the work involved using a C grammar in Backus Naur Form (BNF) like this. What struck me as odd was that the grammar for initializer lists allowed a list to end with a comma (so-called Dangling Comma). I tried it on my compiler, and others, and confirmed that it was allowed.
Example:
<initializer> ::= <assignment-expression>
| { <initializer-list> }
| { <initializer-list> , }
In C:
int array[] = { 1, 2, 3, };
My question: To this day, dangling commas are still a part of C, and other languages too, it seems. Why weren't they removed? (Assuming they don't have any "proper" function (I could be wrong), why did they propagate to other languages?)
Upvotes: 1
Views: 1114
Reputation: 238441
Why weren't they removed?
I don't know if such removal has been considered. I don't know of a reason why such removal would be considered.
To go even further, there would be good reason to add them in case they didn't already exist. They are useful. Indeed, trailing commas have been added in standard revisions into other lists of the languages where they hadn't been allowed before. For example enumerations (C99, C++11). Furthermore, there are proposals to add them to even more lists such as the member init list. I would prefer to see them allowed for example in function calls such as they are allowed in some other languages.
A reason for the allowance of trailing comma is easier modification (less work; less chance of mistake) and clean diffs when programs are modified.
Here are some examples...
Old version without trailing comma:
int array[] = {
1,
2,
3
};
New version:
int array[] = {
1,
2,
3,
4
};
Diff:
< 3
---
> 3,
> 4
Old version with trailing comma:
int array[] = {
1,
2,
3,
};
New version:
int array[] = {
1,
2,
3,
4,
};
Diff:
> 4,
Upvotes: 11
Reputation: 223795
Allowing terminal commas is useful. Given some list:
int Codes[] =
{
37,
74,
88,
};
then:
Upvotes: 6