[SDL] SDL_Event union is blowing my mind

Matthew Bloch mattbee-sdl at soup-kitchen.net
Sun Oct 20 15:21:01 PDT 2002


On Sunday 20 October 2002 22:33, Peter wrote:
>    My question is, how
>    is that possible???  If SDL_Event is a union, it should be able to
>    hold information in either Uint8 type, or the keyboard structure, but
>    not both!!! At least not at the same time.  If somebody could take the
>    time to enlighten a noob, I would be grateful for eternity.

This is a pretty standard C programming trick: where a structure can represent 
one of several different data structures, you can use a union to encompass 
every possible one.  The way you tell the difference is that each structure 
inside the union starts with a common header, in this case a Uint8, so you've 
got:

union
{
     Uint8 type;
     struct { Uint8 type; ... } event1;
     struct { Uint8 type; ... } event2;
     ...
}

so however you reference that "type" field it'll always refer to the same 
point in the data, i.e. the start.  

If you've got any questions on the finer points of C data structure 
organisation, you might get a more in-depth (and doubtless nerdier) answer on 
the USENET comp.lang.c newsgroup.  Also keep a copy of the "C Programming 
Language" handy if you've not already got it, because it tells you everything 
you'll need to know in a very small number of pages:

   http://www.amazon.com/exec/obidos/tg/detail/-/0131103628/

cheers,

-- 
Matthew       > http://www.soup-kitchen.net/
              > ICQ 19482073





More information about the SDL mailing list