Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any relevance to an extra "," in the end of a brace initialization?

Is there a difference between the following two declarations, aside from the obvious - the names:

int main()
{
    char str1[17] = {'H','e','l','l','o'};
    char str2[17] = {'H','e','l','l','o',};
}

What's up with the extra ',' in the second one? Does it mean anything at all?

Both seem to compile just fine and in this case they seem to produce identical strings according to strcmp, which at least is what i expected since the rest of the arrays is filled with zeros.

like image 571
Martin G Avatar asked Feb 13 '23 18:02

Martin G


1 Answers

The trailing comma isn't specific to brace-initialisation and is ubiquitous among programming languages (JSON data format being an outlier).

Except for easy machine generation, one (small) benefit you get from trailing commas is smaller code differences. If you change:

array<string, 20> a = {
    "one",
    "two",
    "three",
};

to

array<string, 20> a = {
    "one",
    "two",
    "three",
    "four",
};

you only get 1 line of difference. If you omit the optional trailing comma, you need to change 2 lines to add or remove the last element. Consistent use of the trailing comma saves you seconds while editing and reading diffs.

like image 116
Kos Avatar answered Feb 15 '23 10:02

Kos