int a[] = {1,2,};为什么在初始值设定项列表中允许尾随逗号? [英] int a[] = {1,2,}; Why is a trailing comma in an initializer-list allowed?
问题描述
也许我不是来自这个星球,但在我看来,以下应该是语法错误:
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
但事实并非如此.当这段代码在 Visual Studio 上编译时,我很惊讶,但我已经学会了不信任 MSVC 编译器就 C++ 规则而言,所以我检查了标准,它是标准也允许.不信你可以看8.5.1的语法规则.
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?
推荐答案
它可以更轻松地生成源代码,也可以更轻松地编写可以在以后轻松扩展的代码.考虑添加额外条目需要什么:
It makes it easier to generate source code, and also to write code which can be easily extended at a later date. Consider what's required to add an extra entry to:
int a[] = {
1,
2,
3
};
...您必须将逗号添加到现有行并添加一个新行.与三个已经后面有一个逗号的情况相比,你只需要添加一行.同样,如果您想删除一行,您可以这样做而不必担心它是否是最后一行,并且您可以重新排列行而无需摆弄逗号.基本上,这意味着您处理线条的方式是一致的.
... you have to add the comma to the existing line and add a new line. Compare that with the case where the three already has a comma after it, where you just have to add a line. Likewise if you want to remove a line you can do so without worrying about whether it's the last line or not, and you can reorder lines without fiddling about with commas. Basically it means there's a uniformity in how you treat the lines.
现在考虑生成代码.类似(伪代码):
Now think about generating code. Something like (pseudo-code):
output("int a[] = {");
for (int i = 0; i < items.length; i++) {
output("%s, ", items[i]);
}
output("};");
无需担心您正在写出的当前项目是第一个还是最后一个.简单多了.
No need to worry about whether the current item you're writing out is the first or the last. Much simpler.
这篇关于int a[] = {1,2,};为什么在初始值设定项列表中允许尾随逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!