How is it legal to reference an undefined type inside a structure?

后端 未结 7 1444
-上瘾入骨i
-上瘾入骨i 2020-12-20 15:52

As part of answering another question, I came across a piece of code like this, which gcc compiles without complaint.

typedef struct {
    struct xyz *z;
} x         


        
7条回答
  •  再見小時候
    2020-12-20 16:32

    The 1st and 2nd cases are well-defined, because the size and alignment of a pointer is known. The C compiler only needs the size and alignment info to define a struct.

    The 3rd case is invalid because the size of that actual struct is unknown.

    But beware that for the 1st case to be logical, you need to give a name to the struct:

    //             vvv
    typedef struct xyz {
        struct xyz *z;
    } xyz;
    

    otherwise the outer struct and the *z will be considered two different structs.


    The 2nd case has a popular use case known as "opaque pointer" (pimpl). For example, you could define a wrapper struct as

     typedef struct {
        struct X_impl* impl;
     } X;
     // usually just: typedef struct X_impl* X;
     int baz(X x);
    

    in the header, and then in one of the .c,

     #include "header.h"
     struct X_impl {
        int foo;
        int bar[123];
        ...
     };
     int baz(X x) {
        return x.impl->foo;
     }
    

    the advantage is out of that .c, you cannot mess with the internals of the object. It is a kind of encapsulation.

提交回复
热议问题