Re: Surprising struct initialization
On Jul 3, 9:05 am, Juha Nieminen <nos...@thanks.invalid> wrote:
struct Point { int x, y; };
struct Line
{
Point endpoint[2];
int weight;
};
Line createLine(int sx, int sy, int ex, int ey)
{
Line l = { sx, sy, ex, ey, 1 };
return l;
}
Both gcc and Visual Studio 2005 compile that happily.
My question would be: Is that *really* correct, or are both compilers
simply being lenient? What are the exact rules for the initialization
blocks of structs?
The compilers are not being lenient - multiple braces can be elided in
an aggregate initializer. Therefore, a program can replace this:
Line l = {{{sx, sy}, {ex, ey}}, 1 };
with:
Line l = {sx, sy, ex, ey, 1 };
as long as there are enough arguments to match the aggregate members.
Otherwise, the braces would be needed. For example:
Line l = {{{sx, xy}}, 1}; // l.endpoint[1] is initialized to {0,
0}
I would leave the braces in an aggregate initializer (even when not
needed) just to make the code more readable.
Greg