Re: Surprising struct initialization
On Jul 3, 6:05 pm, Juha Nieminen <nos...@thanks.invalid> wrote:
I suppose you can never know C++ fully. I would have never
guessed this actually compiles and works:
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;
}
Why shouldn't it?
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 same as in C, at least in the case of POD agglomerates. In
the places I've worked, it's generally considered good practice
to put in all of the braces, e.g.:
Line l = { { { sx, sy }, { ex, ey } }, 1 } ;
but the language allows many or all of them to be elided. (The
exact rules are fairly complex, and in a code review, I would
reject any code that elided some without eliding all. But
initializers like the one you present were common in C, and so
are legal in C++ as well.)
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34