Search code examples
ctypesunions

What does C standard say about a union of two identical types


Is it possible to to have the following assert fail with any compiler on any architecture?

union { int x; int y; } u;
u.x = 19;
assert(u.x == u.y);

Solution

  • C99 Makes a special guarantee for a case when two members of a union are structures that share an initial sequence of fields:

    struct X {int a; /* other fields may follow */ };
    struct Y {int a; /* other fields may follow */ };
    union {X x; Y y;} u;
    u.x.a = 19;
    assert(u.x.a == u.y.a); // Guaranteed never to fail by 6.5.2.3-5.
    

    6.5.2.3-5 : One special guarantee is made in order to simplify the use of unions: if a union contains several structures that share a common initial sequence (see below), and if the union object currently contains one of these structures, it is permitted to inspect the common initial part of any of them anywhere that a declaration of the complete type of the union is visible. Two structures share a common initial sequence if corresponding members have compatible types (and, for bit-fields, the same widths) for a sequence of one or more initial members.

    However, I was unable to find a comparable guarantee for non-structured types inside a union. This may very well be an omission, though: if the standard goes some length to describe what must happen with structured types that are not even the same, it should have clarified the same point for simpler, non-structured types.