Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Accessing C++ struct members by indices and undefined behavior

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading