Nested structs and strict aliasing in c

前端 未结 4 1365
轮回少年
轮回少年 2020-12-08 08:46

Please consider the following code:

typedef struct {
  int type;
} object_t;

typedef struct {
  object_t object;
  int age;
} person_t;

int age(object_t *o         


        
4条回答
  •  生来不讨喜
    2020-12-08 09:14

    One acceptable way that is explicitly condoned by the standard is to make a union of structs with identical initial segment, like so:

    struct tag  { int value;                };
    struct obj1 { int tag;    Foo x; Bar y; };
    struct obj2 { int tag;    Zoo z; Car w; };
    
    typedef union object_
    {
      struct tag;
      struct obj1;
      struct obj2;
    } object_t;
    

    Now you can pass an object_t * p and examine p->tag.value with impunity, and then access the desired union member.

提交回复
热议问题