也许我不是来自这个星球,但在我看来,以下应该是一个语法错误:

int a[] = {1,2,}; //extra comma in the end

但事实并非如此。当这段代码在Visual Studio上编译时,我很惊讶,但我已经学会了不相信MSVC编译器,就c++规则而言,所以我检查了标准,它也是标准允许的。如果你不相信的话,语法规则可以参考8.5.1。

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.

那么,有什么特别的原因,这个多余的逗号是明确允许的吗?


当前回答

它使代码编辑变得容易得多。 我比较editinc c/c++数组元素与编辑json文档-如果你忘记删除最后一个逗号,json将不会解析。(是的,我知道JSON不能手动编辑)

其他回答

我认为是为了便于开发人员使用。

int a[] = {
            1,
            2,
            2,
            2,
            2,
            2, /*line I could comment out easily without having to remove the previous comma*/
          }

此外,如果出于某种原因,你有一个为你生成代码的工具;该工具不需要关心它是否是初始化中的最后一项。

唯一在实践中不被允许的语言是Javascript,它会导致无数的问题。例如,如果你从数组中间复制粘贴一行,粘贴到末尾,并且忘记删除逗号,那么你的网站将对IE访问者完全崩溃。

*理论上这是允许的,但ie浏览器不遵循标准,并将其视为错误

我看到了一个在其他答案中没有提到的用例, 我们最喜欢的宏:

int a [] = {
#ifdef A
    1, //this can be last if B and C is undefined
#endif
#ifdef B
    2,
#endif
#ifdef C
    3,
#endif
};

添加宏到最后处理,将是巨大的痛苦。通过语法上的这个小变化,管理起来很简单。这比机器生成的代码更重要因为用图灵完备语言比用有限的预处理器要容易得多。

每个人都说添加/删除/生成行很容易,但这种语法真正的亮点是合并源文件。假设你有这样一个数组:

int ints[] = {
    3,
    9
};

假设您已经将这段代码签入存储库。

然后你的朋友编辑它,在结尾添加:

int ints[] = {
    3,
    9,
    12
};

你同时编辑它,在开头加上:

int ints[] = {
    1,
    3,
    9
};

从语义上讲,这些类型的操作(添加到开头,添加到结尾)应该是完全合并安全的,你的版本控制软件(最好是git)应该能够自动合并。遗憾的是,情况并非如此,因为你的版本在9后面没有逗号,而你朋友的版本有。然而,如果最初的版本后面有9,他们就会自动生成。

因此,我的经验法则是:如果列表跨越多行,则使用尾随逗号,如果列表在单行上,则不要使用尾随逗号。

如果你这样做,它会很有用:

int a[] = {
  1,
  2,
  3, //You can delete this line and it's still valid
};