本文介绍了是否与额外的“,”,“在大括号初始化的结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下两个声明之间有区别,除了明显的名称:

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?

这两个似乎编译只是罚款,在这种情况下,他们似乎生成相同的字符串根据strcmp,这至少是我期望的,因为

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.

推荐答案

尾部逗号不是特定于大括号初始化,而是无处不在的编程语言(JSON数据格式是一个异常值)。

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",
};

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

您只能得到一行差异。如果省略可选的尾部逗号,则需要更改2行以添加或删除最后一个元素。在编辑和读取差异时,一致使用尾随逗号可以节省您的时间。

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.

这篇关于是否与额外的“,”,“在大括号初始化的结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 18:38