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

前端 未结 6 1120
一整个雨季
一整个雨季 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:45

    In the header file:

    typedef struct _point * Point;
    

    After the compiler sees this it knows:

    • There is a struct called _point.
    • There is a pointer type Point that can refer to a struct _point.

    The compiler does not know:

    • What the struct _point looks like.
    • What members struct _point contains.
    • How big struct _point is.

    Not only does the compiler not know it - we as programmers don't know it either. This means we can't write code that depends on those properties of struct _point, which means that our code may be more portable.

    Given the above code, you can write functions like:

    Point f() {
       ....
    }
    

    because Point is a pointer and struct pointers are all the same size and the compiler doesn't need to know anything else about them. But you can't write a function that returns by value:

    struct _point f() {
      ....
    }
    

    because the compiler does not know anything about struct _point, specifically its size, which it needs in order to construct the return value.

    Thus, we can only refer to struct _point via the Point type, which is really a pointer. This is why Standard C has types like FILE, which can only be accessed via a pointer - you can't create a FILE structure instance in your code.

提交回复
热议问题