How can I hide the declaration of a struct in C?

前端 未结 6 1102
一整个雨季
一整个雨季 2020-12-05 01:13

In the question Why should we typedef a struct so often in C?, unwind answered that:

In this latter case, you cannot return the Point by value, sinc

6条回答
  •  庸人自扰
    2020-12-05 01:49

    What he means is that you cannot return the struct by-value in the header, because for that, the struct must be completely declared. But that happens in the C file (the declaration that makes X a complete type is "hidden" in the C file, and not exposed into the header), in his example. The following declares only an incomplete type, if that's the first declaration of the struct

    struct X;
    

    Then, you can declare the function

    struct X f(void);
    

    But you cannot define the function, because you cannot create a variable of that type, and much less so return it (its size is not known).

    struct X f(void) { // <- error here
      // ...
    }
    

    The error happens because "x" is still incomplete. Now, if you only include the header with the incomplete declaration in it, then you cannot call that function, because the expression of the function call would yield an incomplete type, which is forbidden to happen.

    If you were to provide a declaration of the complete type struct X in between, it would be valid

    struct X;
    struct X f(void);
    
    // ...
    struct X { int data; };
    struct X f(void) { // valid now: struct X is a complete type
      // ...
    }
    

    This would apply to the way using typedef too: They both name the same, (possibly incomplete) type. One time using an ordinary identifier X, and another time using a tag struct X.

提交回复
热议问题