31

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 there a way to set an initial value?

U_U32_F u = 0xffffffff;   // Does not work...is there a correct syntax for this?
1
  • @Prasoon My apologies. I had u32 typdef'ed but not shown in the example.
    – semaj
    Jan 27, 2010 at 18:44

3 Answers 3

41

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 };
2
  • 16
    Just a note that the 2nd example is a C99 feature that's not supported by all compilers. Jan 27, 2010 at 20:04
  • Just another note that the 2nd is valid C++20 as well. May 23, 2022 at 17:03
4

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

2
  • 4
    Microsoft more or less abandoned C and wants you to use C++ (or even better yet: C#); I'm quite content with MinGW, now that gcc-4.4 is out; in the future, Clang/LLVM might be a viable alternative as well if you're looking for a free compiler
    – Christoph
    Jan 27, 2010 at 23:22
  • 2
    The Microsoft C compiler does not (and to my knowledge has not, nor will) conform to any particular standard.
    – Mathieu K.
    Feb 10, 2016 at 9:24
3

Try U_U32_F u = {0xffffffff};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.