Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this use of unions in C valid/compliant?

Tags:

c

struct

unions

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.

like image 915
Daniel Wyatt Avatar asked Feb 11 '17 15:02

Daniel Wyatt


1 Answers

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.

like image 160
Jean-François Fabre Avatar answered Oct 16 '22 08:10

Jean-François Fabre