gcc在数组初始化器中有额外逗号时不会出错。

huangapple go评论58阅读模式
英文:

gcc no error with extra comma in array initializer

问题

这里是一个示例:

int main()
{
  int a[] = {1, 2, 3,};
}

请注意在 3 后面有额外的 ,。即使使用 -Wall 选项编译也没有警告。我在阅读一些 coreutils 代码时注意到数组的最后一个元素后面似乎有逗号。这是未定义行为 (UB) 吗,还是实现定义的,或者就这样没问题?

英文:

Here's an example:

int main () 
{
  int a[] = {1, 2, 3,};
}

Note the extra , after 3. There is no warning even with -Wall and everything. I noticed this while reading some coreutils code that seemed to have a comma after the last element of an array. Is this UB, implementation-defined, or fine as is?

答案1

得分: 5

根据C(和C++)语法,这样的初始化是正确的。

根据C标准

6.7.9 初始化
语法

1 初始化器:
赋值表达式
{ 初始化器列表 }
{ 初始化器列表, }
//...

你可以初始化标量对象,例如

int x = { 10, };

请注意,在C23中,您可以使用空大括号初始化对象(包括可变长度数组),例如

int x = {};

int n = 4;
int a[n] = {};

英文:

According to the C (and C++) grammar such an initialization is correct.

From the C Standard

> 6.7.9 Initialization
> Syntax

1 initializer:
    assignment-expression
    { initializer-list }
    { initializer-list , }
//...

You may initialize such a way even scalar objects as for example

int x = { 10, };

Pay attention to that in C23 you may initialize objects (including variable length arrays) with empty braces as for example

int x = {};

or

int n = 4;
int a[n] = {};

答案2

得分: 2

代码部分不要翻译。以下是翻译好的部分:

"Fine as is. The C standard permits it."

(保持原样。C标准允许这样做。)

英文:

Fine as is. The C standard permits it.

答案3

得分: 0

不仅适用于声明,也适用于更改,您可以将替换为,(以下示例中的结构体中的最后三行):

typedef struct {
    int a;
    int b;
    char c;
} test;

int main(void)
{
    test hi = (test) {
        .a = 0,
        .b = 1,
        .c = 'a',
    };

    hi.a = 6,
    hi.b = 9,
    hi.c = 'r';
}
英文:

Not only for declarations but also for changes, you can replace ; with , (struct in the example below) last three lines:

typedef struct {
    int a;
    int b;
    char c;
} test;

int main(void)
{
    test hi = (test) {
        .a = 0,
        .b = 1,
        .c = 'a',
    };

    hi.a = 6,
    hi.b = 9,
    hi.c = 'r';
}

huangapple
  • 本文由 发表于 2023年6月12日 16:03:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76454633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定