Accessing child variables through higher level structures

后端 未结 8 1826
孤街浪徒
孤街浪徒 2020-12-09 17:41

If I have these structures:

typedef struct { int x; } foo;
typedef struct { foo f; } bar;

Normally you would access x through

8条回答
  •  悲&欢浪女
    2020-12-09 17:52

    C: Highly unrecommended, but doable:

    #include 
    
    #define BAR_STRUCT struct { int x; }
    
    typedef BAR_STRUCT bar;
    
    typedef struct {
        union {
            bar b;
            BAR_STRUCT;
        };
    } foo;
    
    int main() {
      foo f;
      f.x = 989898;
      printf("%d %d", f.b.x, f.x);
    
      return 0;
    }
    

    Anonymous structs are a widly-spread extension in standards before C11.

    C++: The same as in C, you can do here but anonymous structs are not part of any C++ standard, but an extension. Better use inheritance, or do not use this shortcut at all.

    Of course, do not use something like #define x b.x)).

提交回复
热议问题