[cfe-dev] Initialization of an anonymous struct within a class

Shaun Jackman sjackman at bcgsc.ca
Mon Aug 9 12:53:22 PDT 2010


Hi,

I'm not sure whether an anonymous struct within a class is standard, or
a GCC extension that clang attempts to support. In any case, the
following code snippet gives this error:

anonymous-struct.cc:9:16: error: multiple initializations given for non-static member 'y'
        Foo() : x(0), y(0) { }
                      ^~~~
anonymous-struct.cc:9:10: note: previous initialization is here
        Foo() : x(0), y(0) { }
                ^
2 diagnostics generated.

Just for comparison, I've also given code that does not use an anonymous
struct and does compile cleanly.

Please cc me in your reply. Thanks,
Shaun

#define DOES_NOT_WORK 1
#if DOES_NOT_WORK
struct Foo
{
	struct {
		int x;
		int y;
	};
	Foo() : x(0), y(0) { }
};
#else
struct Foo
{
	struct S {
		int x;
		int y;
	} s;
	Foo() : s((S){ .x = 1, .y = 2}) { }
};
#endif

#include <iostream>

int main()
{
	Foo foo;
#if DOES_NOT_WORK
	std::cout << foo.x << ' ' << foo.y << '\n';
#else
	std::cout << foo.s.x << ' ' << foo.s.y << '\n';
#endif
	return 0;
}





More information about the cfe-dev mailing list