开发者

Can a union be initialized in the declaration?

开发者 https://www.devze.com 2022-12-18 10:46 出处:网络
For example, say we have a union typedef union { unsigned long U32; float f; }U_U32_F; When a variable of t开发者_如何学Gohis union type is declared, is there a way to set an initial value?

For example, say we have a union

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

When a variable of t开发者_如何学Gohis union type is declared, is there a way to set an initial value?

U_U32_F u = 0xffffffff;   // Does not work...is there a correct syntax for this?


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 };


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.)


Try U_U32_F u = {0xffffffff};

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号