I found on this official gnu gcc website that they initialize structures like that:
struct f1 {
int x; int y[];
} f1 = { 1, { 2, 3, 4 } };
struct f2 {
struct f1 f1; int data[3];
} f2 = { { 1 }, { 2, 3, 4 } };
At first I thought it was a default initialization for the struct, but I tested it and it doesn't auto-initialize the struct when declared, so what's the point of using this (I compiled my program with gcc of course).
The code I tried:
#include <stdio.h>
struct a{
int x;
int y;
} a = {42, 42};
int main(void)
{
struct a foo;
printf("%d\n%d\n", foo.x, foo.y);
return (0);
}
And it outputs random uninitialized data instead of
42
42
Your confusion seems to stem from the fact that you do not understand the syntax.
struct f1 {
int x; int y[];
} f1 = { 1, { 2, 3, 4 } };
defines a variable named f1
with it's members initialized.
In your example, you also have a variable a
initialized in the global scope, but you also have the same variable a
in main
scope, which is left uninitialized.
I misunderstood, this is equivalent to struct f1 f1 = { 1, {2, 3, 4}};
, the fact that they used the same name f1
made me think that this was a new syntax.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.