]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/doc/gcc/extensions-to-the-c-language-family/cast-to-a-union-type.rst
sphinx: add missing trailing newline
[thirdparty/gcc.git] / gcc / doc / gcc / extensions-to-the-c-language-family / cast-to-a-union-type.rst
1 ..
2 Copyright 1988-2022 Free Software Foundation, Inc.
3 This is part of the GCC manual.
4 For copying conditions, see the copyright.rst file.
5
6 .. index:: cast to a union, union, casting to a
7
8 .. _cast-to-union:
9
10 Cast to a Union Type
11 ********************
12
13 A cast to a union type is a C extension not available in C++. It looks
14 just like ordinary casts with the constraint that the type specified is
15 a union type. You can specify the type either with the ``union``
16 keyword or with a ``typedef`` name that refers to a union. The result
17 of a cast to a union is a temporary rvalue of the union type with a member
18 whose type matches that of the operand initialized to the value of
19 the operand. The effect of a cast to a union is similar to a compound
20 literal except that it yields an rvalue like standard casts do.
21 See :ref:`compound-literals`.
22
23 Expressions that may be cast to the union type are those whose type matches
24 at least one of the members of the union. Thus, given the following union
25 and variables:
26
27 .. code-block:: c++
28
29 union foo { int i; double d; };
30 int x;
31 double y;
32 union foo z;
33
34 both ``x`` and ``y`` can be cast to type ``union foo`` and
35 the following assignments
36
37 .. code-block:: c++
38
39 z = (union foo) x;
40 z = (union foo) y;
41
42 are shorthand equivalents of these
43
44 .. code-block:: c++
45
46 z = (union foo) { .i = x };
47 z = (union foo) { .d = y };
48
49 However, ``(union foo) FLT_MAX;`` is not a valid cast because the union
50 has no member of type ``float``.
51
52 Using the cast as the right-hand side of an assignment to a variable of
53 union type is equivalent to storing in a member of the union with
54 the same type
55
56 .. code-block:: c++
57
58 union foo u;
59 /* ... */
60 u = (union foo) x == u.i = x
61 u = (union foo) y == u.d = y
62
63 You can also use the union cast as a function argument:
64
65 .. code-block:: c++
66
67 void hack (union foo);
68 /* ... */
69 hack ((union foo) x);