Syntax to initialize an anonymous union

c++, unions

Solution

This works (at least in gcc 4.7.2):

union { int i; float f; } x = {1};

Notice that the type (i.e. the `union`) is anonymous but its instanciation is called `x`.

What you were trying to achieve (e.g. `union { int i; float f; }{in};`) doesn't compile but suppose it did. Then you would be creating an unnamed object (a temporary) of an unnamed type. The temporary would be destroyed at the end of the expression and, therefore, this statement would have no effect. So what's the point?

Problem

If I declare an anonymous union in a function… ``` void f(int in) { union { int i; float f; }; // … } ``` …does syntax exist to initialize it (other than assigning to `i` or `f` in another statement? A quick look at the spec suggests no. The obvious ones don’t compile: ``` // Nope: union { int i = in; float f; }; union { int i; float f; } = in; union { int i; float f; } = {in}; union { int i; float f; }{in}; union { int i; float f; }(in); ```

Original source