I've been diving into SDL and came across some tutorials where they mention unions like SDL_Event. I see it has a member called 'type' that's an integer. I can't quite wrap my head around how this relates to the SDL_EventType enum, which includes constants like SDL_QUIT. Why can I just use 'e.type' to check against SDL_QUIT? Shouldn't it be something like 'e.SDL_EventType == SDL_QUIT' instead? I'm feeling really puzzled, much like when I was in school trying to understand complicated math without the practical application explained. Anyone able to clarify this?
5 Answers
The 'type' is just an integer representing the enum value, so when you write 'e.type', it's giving you the numeric value of the event type. This is like calling a field in a struct. The enum SDL_EventType defines a few values, including SDL_QUIT, but it's not part of the event structure directly. You access 'type' on its own because that's how unions work; they combine various structs and the first member is used for quick access.
So basically, you have the SDL_Event union that has an int as its first member called 'type', which indicates what kind of event it is. The enum SDL_EventType is just a series of constants like SDL_QUIT that effectively map to integers. When you do 'if( e.type == SDL_QUIT )', you're checking if the integer in 'type' matches the integer value that SDL_QUIT represents. This is just the way unions simplify handling different types of events.
Another way to think about it is like this: when you create that union, SDL made sure all event types start with a 'type' field. So instead of going through each specific struct every time, you can directly check 'e.type'. The C++ rules allow this by recognizing that the initial part of the type is the same across the different structs—so it’s efficient and cleaner!
To add on to that, every event (like key events, quit events, etc.) starts with the same 'type' because of how SDL is structured, allowing for this shorthand access. You’re right that enums typically get accessed through their struct members, but unions let you bypass that if they share this common sequence. It's kind of breaking the norms but totally works in this situation.
You're right in thinking that there’s a lot of confusion with unions and access types, but the magic in SDL comes from its design. Every event struct that could be in the union starts with an integer member for 'type'. It creates a common initial sequence—this way, you can just reference 'e.type' to find out what type of event you're dealing with. It's a neat trick that makes using the union much simpler than it would otherwise be.

Related Questions
How To: Running Codex CLI on Windows with Azure OpenAI
Set Wordpress Featured Image Using Javascript
How To Fix PHP Random Being The Same
Why no WebP Support with Wordpress
Replace Wordpress Cron With Linux Cron
Customize Yoast Canonical URL Programmatically