IBM extension

Cast to union type (C only)

Casting to a union type is the ability to cast a union member to the same type as the union to which it belongs. Such a cast does not produce an lvalue, unlike other casts. The feature is supported as an extension to C99, implemented to facilitate porting programs developed with GNU C.

Only a type that explicitly exists as a member of a union type can be cast to that union type. The cast can use either the tag of the union type or a union type name declared in a typedef expression. The type specified must be a complete union type. An anonymous union type can be used in a cast to a union type, provided that it has a tag or type name. A bit field can be cast to a union type, provided that the union contains a bit field member of the same type, but not necessarily of the same length.

Casting to a nested union is also allowed. In the following example, the double type dd can be cast to the nested union u2_t.

int main() {
   union u_t {
      char a;
      short b;
      int c;
      union u2_t {
         double d;
   union u_t U;
   double dd = 1.234;
   U.u2 = (union u2_t) dd;      // Valid.
   printf("U.u2 is %f\n", U.u2);

The output of this example is:

U.u2 is 1.234

A union cast is also valid as a function argument, part of a constant expression for initialization, and in a compound literal statement.

Related information

End of IBM extension