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?)
CodePudding user response:
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. Example:
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,
CodePudding user response:
Allowing terminal commas is useful. Given some list:
int Codes[] =
{
37,
74,
88,
};
then:
- For human maintenance of lists, we can easily add or delete lines without fiddling with commas. If a terminal comma were not allowed, the appending a new line would also require editing the exiting the previous line to add a comma, and deleting the last line would also require editing the previous line to remove its comma.
- For machine-generated lists, we do not need to include code in the loop generating the list to treat the last list item differently.