PSkocik PSkocik - 1 month ago 14
C Question

Union members of the same type

Suppose I have a union u with two members

a
and
b
of the same type (e.g., int).

union u{
int a,b;
char c;
};


If I write to
a
, pass it to a function by value, and the function reads from
b
, expecting to get the
a
value, will there be any issues, considering
a
and
b
have the same type? Do the member reads need to mirror member writes exactly?

Answer

Yes, that's fine.

The standard (C11 draft) says:

[...] 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 completed type of the union is visible

Here the two integers can be considered to be (very simple) structures that share the same initial sequence.

Even ignoring that, there's also:

If the member used to read the contents of a union object is not the same as the member last used to store a value in the object, the appropriate part of the object representation of the value is reinterpreted as an object representation in the new type

Reinterpreting an int as an int is pretty safe. :)