MSVC Ignores Empty Initializer List in C
Before C23, ISO C forbids empty initializer braces. Take the following code as an example:
#include <stdio.h>
typedef struct tagFoo {
int i;
} Foo;
static Foo foos[3] = {
{},
{1},
{2},
};
int main(void){
printf("sizeof(foos): %zu\n", sizeof(foos));
printf("sizeof(Foo): %zu\n", sizeof(Foo));
printf("foo[0].i: %d\n", foos[0].i);
printf("foo[1].i: %d\n", foos[1].i);
printf("foo[2].i: %d\n", foos[2].i);
return 0;
}
Compile the program in gcc 14.2 with -pedantic
, we got:
sizeof(foos): 12
sizeof(Foo): 4
foo[0].i: 0
foo[1].i: 1
foo[2].i: 2
Without -pedantic
, the result will not change, despite no warning would be thrown.
However, in MSVC v19.40 (vs 17.10), the code compiles without any warning, but the result is weird:
sizeof(foos): 12
sizeof(Foo): 4
foo[0].i: 1
foo[1].i: 2
foo[2].i: 0
MSVC ignores the empty initializer list, and shifted the struct array.
FYI, currently C23 empty initializers are partially supported in gcc, and not supported in MSVC.