Can a union be initialized in the declaration?

后端 未结 3 1763
庸人自扰
庸人自扰 2020-11-29 08:12

For example, say we have a union

typedef union {
unsigned long U32;
float f;
}U_U32_F;

When a variable of this union type is declared, is t

相关标签:
3条回答
  • 2020-11-29 08:47

    Note that per-member union initialization doesn't work on pre-C99 compilers, of which there is a depressing number out there. The current Microsoft C compiler doesn't support it, for example. (I vaguely recall it doesn't even support first-member initialization, which goes back to K&R II, but I might be wrong about that.)

    0 讨论(0)
  • 2020-11-29 08:49

    Use an initializer list:

    U_U32_F u = { 0xffffffff };
    

    You can set other members than the first one via

    U_U32_F u = { .f = 42.0 };
    
    0 讨论(0)
  • 2020-11-29 08:51

    Try U_U32_F u = {0xffffffff};

    0 讨论(0)
提交回复
热议问题