Handmade Hero»Forums»Code
Simon Anciaux
1335 posts
Question about v4 definition syntax
Since every part of a union is always accessible, is there a reason to not write v4 like this :
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
union v4
{
	struct
	{
		real32 x, y, z, w;
	};
	struct
	{
		v3 xyz;
	};
	struct
	{
		real32 r, g, b, a;
	};
	struct
	{
		v3 rgb;
	};

	real32 E[4];
};

instead of
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
union v4
{
    struct
    {
        union
        {
            v3 xyz;
            struct
            {
                real32 x, y, z;
            };
        };
        
        real32 w;        
    };
    struct
    {
        union
        {
            v3 rgb;
            struct
            {
                real32 r, g, b;
            };
        };
        
        real32 a;        
    };
    real32 E[4];
};

I haven't watched day 96 and 97 (only grabed the last code files), sorry if it's talked about in those episodes.
Casey Muratori
801 posts / 1 project
Casey Muratori is a programmer at Molly Rocket on the game 1935 and is the host of the educational programming series Handmade Hero.
Question about v4 definition syntax
I don't think there's any reason not to do it that way, but I guess I haven't tried it... it looks reasonable, though!

- Casey
4 posts
Question about v4 definition syntax
Edited by dvkirn on
Clang did freak out on me compiling the bottom one. It seemed to think there was only 3 elements in a v4 when declaring with an initializer list:

1
v4 foo = {1, 2, 3, 4};

I got this error: "Excessive elements in union initializer." So if anything the top one is actually better! Looking into it further it seems like the initializer is bound to the first element (in this case another union whose first element is a v3), which apparently is something I've never run into before.
Simon Anciaux
1335 posts
Question about v4 definition syntax
Ok, thanks for the answers.
Simon Anciaux
1335 posts
Question about v4 definition syntax
Just to be "complete" we can also remove struct around v3.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
union v4
{
	struct
	{
		real32 x, y, z, w;
	};

	v3 xyz;
	v2 xy;

	struct
	{
		real32 r, g, b, a;
	};

	v3 rgb;

	real32 E[4];
};
Mārtiņš Možeiko
2559 posts / 2 projects
Question about v4 definition syntax
A bit related to v4 - after Day 99 now you have two different functions to make v3 from v2:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
inline v3
V3(v2 XY, real32 Z)
{
    v3 Result;

    Result.x = XY.x;
    Result.y = XY.y;
    Result.z = Z;

    return(Result);
}

inline v3
ToV3(v2 XY, real32 Z)
{
    v3 Result;

    Result.xy = XY;
    Result.z = Z;

    return(Result);
}


How about removing one of them? And if remove ToV3, then change "ToV4" to "V4" so making v4 from v3 is similar how v3 is made from v2.