这段C代码为什么要编译?C结构类型定义
我编写了以下程序:这段C代码为什么要编译?C结构类型定义,c,compiler-construction,struct,C,Compiler Construction,Struct,我编写了以下程序: 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;
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;
}
谁能给我解释一下发生了什么事吗?你说:
blah blah未声明为结构
事实上,它有:
typedef struct blahblah {
int x;
int y;
} Coordinate;
这既是一个typedef坐标
,也是一个struct blahblah
的定义。定义是:
- 定义名为
struct blahblah
- 它有两个成员,
和intx
李>inty
- 另外,创建一个名为
的类型定义,它相当于Coordinate
struct blahblah
struct blahblah {
int x;
int y;
};
typedef struct blahblah Coordinate;
由于这会为结构类型(
struct blahblah
)和Coordinate
)创建两个名称,因此这两个类型名称都可以用于声明变量。typedef
定义新的用户定义数据类型,但不会使旧定义无效。例如,typedef int
不会使int
无效。同样,您的blahblah
仍然是一个有效的定义结构!坐标只是一种新类型 typedef用于创建一种类型到另一种类型的别名。实际上,您是在typedef本身中声明“struct blahblah”。这有点令人困惑,但正如@Timothy和其他人指出的,这是一个有效的定义 我不太明白<代码>结构blahblah当然已经声明为结构,它就在示例的顶部。