Extending a struct in C

前端 未结 11 918
你的背包
你的背包 2020-12-23 15:54

I recently came across a colleague\'s code that looked like this:

typedef struct A {
  int x;
}A;

typedef struct B {
  A a;
  int d;
}B;

void fn(){
  B *b;         


        
11条回答
  •  不知归路
    2020-12-23 16:27

    Anything that circumvents type checking should generally be avoided. This hack rely on the order of the declarations and neither the cast nor this order can be enforced by the compiler.

    It should work cross-platform, but I don't think it is a good practice.

    If you really have deeply nested structures (you might have to wonder why, however), then you should use a temporary local variable to access the fields:

    A deep_a = e->d.c.b.a;
    deep_a.x = 10;
    deep_a.y = deep_a.x + 72;
    e->d.c.b.a = deep_a;
    

    Or, if you don't want to copy a along:

    A* deep_a = &(e->d.c.b.a);
    deep_a->x = 10;
    deep_a->y = deep_a->x + 72;
    

    This shows from where a comes and it doesn't require a cast.

    Java and C# also regularly expose constructs like "c.b.a", I don't see what the problem is. If what you want to simulate is object-oriented behaviour, then you should consider using an object-oriented language (like C++), since "extending structs" in the way you propose doesn't provide encapsulation nor runtime polymorphism (although one may argue that ((A*)b) is akin to a "dynamic cast").

提交回复
热议问题