简体   繁体   English

为什么这个C代码编译? C struct typdef

[英]Why does this C code compile? C struct typdef

I wrote the following program: 我写了以下程序:

typedef struct blahblah {
    int x;
    int y;
} Coordinate;

int main () {
   Coordinate p1;
   p1.x = 1;
   p1.y = 2;

   //blah blah has not been declared as a struct, so why is it letting me do this?
   struct blahblah p2;
   p2.x = 5;
   p2.y = 6; 
}

Can anyone explain to me what's going on? 任何人都可以向我解释发生了什么事吗?

You said: 你说:

blah blah has not been declared as a struct, blah blah尚未被声明为结构,

Actually, it has: 实际上,它有:

typedef struct blahblah {
    int x;
    int y;
} Coordinate; 

This is both a typedef Coordinate , and a definition of struct blahblah . 这既是typedef Coordinate ,也是struct blahblah的定义。 What the definition says is: 定义的含义是:

  • define a data-type called struct blahblah 定义一个名为struct blahblah的数据类型
  • It has two members, int x and int y . 它有两个成员, int xint y
  • Also, make a type definition called Coordinate that is equivalent to struct blahblah 另外,创建一个名为Coordinate的类型定义,它等同于struct blahblah

Your struct declaration is equivalent to 您的结构声明等同于

struct blahblah {
    int x;
    int y;
};
typedef struct blahblah Coordinate;

Since this creates two names for the struct type ( struct blahblah ) and Coordinate , both type names are permissible for declaring variables. 由于这为结构类型( struct blahblah )和Coordinate创建了两个名称,因此两个类型名称都允许用于声明变量。

typedef defines a new user-defined data type but DOES NOT invalidate the old definition . typedef定义新的用户定义数据类型,但不会使旧定义无效 For example typedef int INT will not invalidate int . 例如, typedef int INT不会使int无效。 Likewise your blahblah is still a valid defined structure! 同样,你的blahblah仍然是一个有效的定义结构! And Coordinate is just a new type! 而Coordinate只是一种新型!

You declared blahblah as a struct in your typedef. 你在你的typedef中声明blahblah是一个结构。 A typedef is simply an easy way of referencing struct blahblah. typedef只是引用struct blahblah的简单方法。 But struct blahblah exists and that's why you can give it a typedef. 但是结构blahblah存在,这就是为什么你可以给它一个typedef。

typedef is used to create an alias of one type to another. typedef用于创建一种类型的别名。 You're actually declaring the 'struct blahblah' in the typedef itself. 你实际上是在typedef本身声明'struct blahblah'。 It's a bit confusing but as @Timothy and others note it's a valid definition. 这有点令人困惑,但正如@Timothy和其他人所说,这是一个有效的定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM