Union members of the same type

Suppose I have a union u with two members a and b the same type (e.g. int).

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

If I write to a , pass it to the function by value, and the function reads from b , expecting to get the value of a , will there be problems considering a and b are of the same type? Does a member need to be read in order to accurately record member records?

+5
source share
1 answer

Yes, that's great.

The standard (draft C11) states:

[...] if the union contains several structures that have a common initial (see below), and if the object of the union currently contains one of these structures, it is allowed to check the common initial part of any of them at any place where the declaration is completed type of union visible

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

Even ignoring this, also:

If the element used to read the contents of the union object is not the same since the last element was used to store the value in the object, the corresponding part of the object representation of the value is reinterpreted as representing the object in a new type

Rethinking int as int pretty safe. :)

+4
source

Source: https://habr.com/ru/post/1258802/


All Articles