Struct literals bug ?

John Colvin john.loughran.colvin at gmail.com
Sun Sep 29 10:12:57 PDT 2013


On Sunday, 29 September 2013 at 16:36:22 UTC, andrea9940 wrote:
> I think that I found a bug in the initialization of a struct.
> This program throws "a.v.y != 0" but all assert should pass...
> (I'm using the latest dmd version available)
>
> Code: http://pastebin.com/VHQP8DaE

I'm not sure what the rules are for initialisation of unions, or 
even if they are defined. What's happening is that the memory is 
being initialised first by your explicit initialisers for xyza 
and then again by the defaul initialisers (nan in the case of 
float) for rgba.

There's no need for a union though in that example, as the types 
are the same. Would this work for you?

struct Vector(ubyte size, Type)
{
	static assert(size < 5);
	static if (size > 0)
	{
		Type x = 0;
		alias r = x;
	}
	static if (size > 1)
	{
		Type y = 0;
		alias g = y;
	}
	static if (size > 2)
	{
		Type z = 0;
		alias b = z;
	}
	static if (size > 3)
	{
		Type w = 1;
		alias a = w;
	}
}

struct A
{
	int n;
	Vector!(3, float) v;
}

unittest
{
	Vector!(3, float) v;
	assert(v.x == 0, "v.x != 0");
	assert(v.y == 0, "v.y != 0");
	assert(v.z == 0, "v.z != 0");
	A a;
	assert(a.v.x == 0, "a.v.x != 0");
	assert(a.v.y == 0, "a.v.y != 0");
	assert(a.v.z == 0, "a.v.z != 0");
}


More information about the Digitalmars-d-learn mailing list