Say, we would like to access members of a C++ structure by indices. It could be conveniently implemented using unions:
#include <iostream>
struct VehicleState
{
struct State
{
double x, y, v, yaw;
};
union
{
State st;
double arr[4];
};
};
int main()
{
VehicleState state;
state.st.x = 1;
state.st.y = 2;
state.st.v = 3;
state.st.yaw = 4;
for (auto value : state.arr)
std::cout << value << std::endl;
}
Unfortunately, it is undefined behavior to read from the member of the union that wasn’t most recently written. That said, I haven’t found any compiler or a platform where it would not work as expected. Could you tell me what was the rationale for calling it undefined behavior rather than standardizing it?
>Solution :
Actually it’s perfectly fine to read from a union member other than the one you have written too as long as you only access a common prefix. So
union {
State st;
struct {
double x;
};
} state;
state.st.x = 1;
if (state.x == 1) // perfectly fine.
The problem is that the rules for the layout of structs is complicated and a lot is implementation defined. The struct with 4 doubles could have padding between doubles for some reason and then your array of doubles wouldn’t access the same bytes.
Unless the standard starts mandating the padding or describes when padding must be equal for unions to work like you ask this can’t be allowed.
I recommend watching named tupples