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?