PSkocik PSkocik - 1 year ago 89
C Question

Union members of the same type

Suppose I have a union u with two members

of the same type (e.g., int).

union u{
int a,b;
char c;

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

Answer Source

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. :)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download