ctypesundefined-behaviorunionsmemory-alignment

Undefined behavior with unions


While working with 3D points, I came across this approach to type definition :

union point_3d {
    struct {
        GLdouble x, y, z;
    } coord;

    GLdouble tab[ 3 ];
};

Thus, the coordinates can be accessed both by name and by subscript, using for example p.coord.x and p.tab.[0] interchangeably.

This is more useful than just typedef GLdouble point_3d[3]; in that unions support direct assignment (and of course, we can access coordinates by name), but also more useful than struct point_3d { glDouble x, y, z; }; in that the type is directly iterable without using sizeof.

But, the actually important question : Is this safe ? Is this portable ? I haven't been able to find anything to suggest it isn't, but I haven't been able to confirm with that it is guaranteed, so I'm asking here to people hopefully more knowledgeable than I.

(while I am interested to know if this works on Windows, I'm specifically referring to POSIX portability. Windows is only of secondary importance to me )


Solution

  • C allows type-punning through unions.

    That means you can write to one member of the union (for example the structure), and read from another member (the array). And the opposite way of course.

    The big possible problem is if the structure contain any padding between elements or not. If it does then it does not match up with the array. It's unlikely in this case though.