C联盟 - 请解释

ser*_*aev 4 c sdl-2

据我所知,C中的联合一次只能保存1个值,我真的不明白C中的代码是如何理解的,因为event.window不能与event.type同时填充?

while(SDL_PollEvent(&event)) {
switch(event.type)
{
case SDL_WINDOWEVENT:
    switch(event.window.event)
Run Code Online (Sandbox Code Playgroud)

该事件定义为:

typedef union SDL_Event
{
    Uint32 type;                    /**< Event type, shared with all events */
    SDL_CommonEvent common;         /**< Common event data */
    SDL_WindowEvent window;         /**< Window event data */
    SDL_KeyboardEvent key;          /**< Keyboard event data */
    SDL_TextEditingEvent edit;      /**< Text editing event data */
    SDL_TextInputEvent text;        /**< Text input event data */
    SDL_MouseMotionEvent motion;    /**< Mouse motion event data */
    SDL_MouseButtonEvent button;    /**< Mouse button event data */
    SDL_MouseWheelEvent wheel;      /**< Mouse wheel event data */
    SDL_JoyAxisEvent jaxis;         /**< Joystick axis event data */
    SDL_JoyBallEvent jball;         /**< Joystick ball event data */
    SDL_JoyHatEvent jhat;           /**< Joystick hat event data */
    SDL_JoyButtonEvent jbutton;     /**< Joystick button event data */
    SDL_JoyDeviceEvent jdevice;     /**< Joystick device change event data */
    SDL_ControllerAxisEvent caxis;      /**< Game Controller axis event data */
    SDL_ControllerButtonEvent cbutton;  /**< Game Controller button event data */
    SDL_ControllerDeviceEvent cdevice;  /**< Game Controller device event data */
    SDL_QuitEvent quit;             /**< Quit request event data */
    SDL_UserEvent user;             /**< Custom event data */
    SDL_SysWMEvent syswm;           /**< System dependent window event data */
    SDL_TouchFingerEvent tfinger;   /**< Touch finger event data */
    SDL_MultiGestureEvent mgesture; /**< Gesture event data */
    SDL_DollarGestureEvent dgesture; /**< Gesture event data */
    SDL_DropEvent drop;             /**< Drag and drop event data */

    /* This is necessary for ABI compatibility between Visual C++ and GCC
       Visual C++ will respect the push pack pragma and use 52 bytes for
       this structure, and GCC will use the alignment of the largest datatype
       within the union, which is 8 bytes.

       So... we'll add padding to force the size to be 56 bytes for both.
    */
    Uint8 padding[56];
} SDL_Event;
Run Code Online (Sandbox Code Playgroud)

Bas*_*tch 6

每个骨料(structS ^大概)成员SDL_CommonEvent common;,SDL_WindowEvent window;, SDL_KeyboardEvent key;等...的union SDL_Event开始与一些Uint32 字段,以type和普通type场在每个工会成员相同的地址和大小.

因此,虽然的确是工会在内存中进行一次只有一个字段(换句话说,所有的工会成员有相同的地址),他们每个人开始用typeevent.type有意义的; 它取得了那个type.

这种习语是C中实现标记联合的常用方法.