I can not find a definite answer to the next question.
As far as I can remember, the union
has always been used not so much for alternately storing different data in one place, but for flexible access to some pieces of these same data. In other words, for writing data of one type and reading data of another type.
For example:
typedef union u_color_pack { uint8_t b[4]; uint32_t raw; } color_pack; // … uint8_t color_check(const uint32_t _raw) { color_pack color; color.raw = _raw; if (color.b[0] == 0) { return 0; } return 1; }
color_pack
allows color_pack
to work with color as raw data of type uint32_t
or directly access individual bytes (colors). Yes, I understand that the given code depends on the order of bytes, but such code is usually written with the expectation of a strictly defined order of bytes.
So, the problem is that some people say that it is impossible to read from the union
data of type A
, if before that the union
has written the data of type B
Some say that this situation is uncertain behavior. Others - what is the behavior defined by the implementation.
What do the C
and C++
standards say about this issue? Is what they say different?
union
members are standard-layout types with the same set of fields at the beginning — then you can refer to any of these fields. For references to the standard, it is better to wait for someone like AnT. :) - HolyBlackCat#ifdef else endif
, it makes sense only if you write a cross-processor application, or some kind of cross-platform with special platforms. If you are writing under Windows or ordinary x86 / x64 Linux and do not plan to change to another platform's CPU, then this should not be taken into account. - nick_n_aunion
? - HolyBlackCatAnt
- MGNeo