clanguage-lawyer

Is this a standard feature in C


I can't understand if this feature is standard or only some weird stuff.

struct A {
    int field_1;
    int field_2;
};

struct B {
    struct A super;
};

int main() {
    struct B b;

    // Normally i must access like that to field_2
    b.super.field_2 = 10;
    
    // Is legal to access in this manner?
    struct A* generic_ref = (struct A*)&b;
    generic_ref->field_2 = 10;

    return 0;
}

I tried on gcc and it seems to work, but i think that can be something that can break in some more complicated situations.


Solution

  • This is allowed, as a pointer to a struct can be converted to a pointer to its first member.

    This is specifically spelled out in section 6.7.2.1p15 of the C standard:

    A pointer to a structure object, suitably converted, points to its initial member