Search code examples
cstructunions

Is this use of unions in C valid/compliant?


Given these structures:

typedef struct {
    //[...]
} StructA;

typedef struct {
    StructA a;
    //[...]
} StructB;

typedef union {
    StructA a;
    StructB b;
} Union;

Are the two access methods below equivalent and not undefined?

Union u;
memcpy(&u.b, /*...*/); //Pretend I populated StructB here
u.a;    // Method 1
u.b.a;  // Method 2

Note that StructA happens to be the first member of StructB.

I spotted this in a codebase that works, I'm just wondering if it is standard or if there are any alignment gotchas.


Solution

  • typedef union {
        StructA a;
        StructB b;
    } Union;
    

    a has the same offset as b in the union: 0

    a has offset 0 in StructB.

    The calls are equivalent.