Handmade Hero»Forums»Code
5 posts
Day 017: game_controller_input bounds checking
Edited by Salads on
I thought of an easier way to bounds check the game_controller_input union in handmade.h

The original assert for reference
1
Assert((&Input->Controllers[0].Terminator - &Input->Controllers[0].Buttons[0]) == (ArrayCount(Input->Controllers[0].Buttons) - 1));


Since game_controller_input is a union, couldn't we copy-pasta the anonymous struct and add an identifier to the end of it?

 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
struct game_controller_input
{
	bool32 IsConnected;
	bool32 IsAnalog;

	real32 StickAverageX;
	real32 StickAverageY;

	union
	{
		game_button_state Buttons[12];
		struct
		{
			game_button_state MoveUp;
			game_button_state MoveDown;
			game_button_state MoveLeft;
			game_button_state MoveRight;

			game_button_state ActionUp;
			game_button_state ActionDown;
			game_button_state ActionLeft;
			game_button_state ActionRight;

			game_button_state LeftShoulder;
			game_button_state RightShoulder;

			game_button_state Back;
			game_button_state Start;
		};

		struct
		{
			game_button_state MoveUp;
			game_button_state MoveDown;
			game_button_state MoveLeft;
			game_button_state MoveRight;

			game_button_state ActionUp;
			game_button_state ActionDown;
			game_button_state ActionLeft;
			game_button_state ActionRight;

			game_button_state LeftShoulder;
			game_button_state RightShoulder;

			game_button_state Back;
			game_button_state Start;
		} u;
	};
};


This way, the assert becomes much more straightforward.

Comparison:
1
Assert((&Input->Controllers[0].Terminator - &Input->Controllers[0].Buttons[0]) == (ArrayCount(Input->Controllers[0].Buttons) - 1));

1
Assert(sizeof(Input->Controllers[0].Buttons) == sizeof(Input->Controllers[0].u));


I remember seeing in the MSDN docs somewhere that they did this with one of the structs we used. I'm trying to find info about this technique online but I don't know what it's called... :(
Mārtiņš Možeiko
2562 posts / 2 projects
Day 017: game_controller_input bounds checking
Edited by Mārtiņš Možeiko on
Why would you want that copy&paste?
Imho that is very ugly. Better way would be to remove first structure, rename u to Button, and use it like "Input->Button.MoveUp.IsDown".

This is called "anonymous structure". You are not giving structure type name, but directly using it for member type.
5 posts
Day 017: game_controller_input bounds checking
I agree it IS very ugly...

Also thanks! :)