为什么允许`typedef struct xx`?

blu*_*ote 0 c

我正在阅读《现代C》这本书,很惊讶地发现以下代码有效

typedef struct point point;
struct point {
    int x;
    int y;
};

int main() {
   point p = { .x = 1, .y = 2 };
}
Run Code Online (Sandbox Code Playgroud)

但是,这本书没有详细介绍。这是如何运作的?为什么pointmain()typedefstruct point定义之后呢?

dbu*_*ush 6

该行typedef struct point point;有两件事:

  • 它创建了一个向前声明struct point
  • 它创建了一个类型别名struct point叫做point

如果您需要在结构完全定义之前就知道其退出,则前向声明很有用,例如:

typedef struct x X;

typedef struct y {
    int a;
    X *x;
} Y;

 struct x {
     int b;
     Y *y;
 };
Run Code Online (Sandbox Code Playgroud)

  • 我认为`typedef struct x X;`应该是`typedef struct XX;` (3认同)