gcc no error with extra comma in array initializer

105 views Asked by At

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?

3

There are 3 answers

0
Mark Adler On

Fine as is. The C standard permits it.

11
Vlad from Moscow On

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] = {};
1
Hexagon On

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';
}