【发布时间】:2019-08-12 10:07:16
【问题描述】:
结构体开头的名字和结构体结尾的名字不同是什么意思?例如:
struct book{
char title[50];
int year;
}boo;
例如
typedef struct book{
char title[50];
int year;
}boo;
【问题讨论】:
结构体开头的名字和结构体结尾的名字不同是什么意思?例如:
struct book{
char title[50];
int year;
}boo;
例如
typedef struct book{
char title[50];
int year;
}boo;
【问题讨论】:
在第一种情况下,您定义一个结构并立即创建其类型的变量。
struct book{
char title[50];
int year;
}boo; // <== boo is already a variable, you can start using it; boo.year = 2019;
在第二个示例中,您创建了一个 typedef,说明“boo”声明现在与您的结构相同,因此您可以在之后使用该“boo”创建变量。在这种情况下,结构声明时不会创建任何变量。
typedef struct book{
char title[50];
int year;
}boo;
boo a, b; // <== here you create variables
【讨论】:
这个例子
struct book{
char title[50];
int year;
}boo;
创建一个名为boo 的变量,其类型为struct book。
另一个例子:
typedef struct book{
char title[50];
int year;
}boo;
将boo 定义为与struct book 相同的类型,一种别名排序。
【讨论】:
typedef 定义了“别名排序”。它实际上定义了一个别名,而不是排序。
struct book 是类型名称(如int 或double)。类型由大括号之间的东西定义 - { char title[50]; int year; }。在第一个 sn-p 中,boo 被声明为 struct book 类型的 object(变量)。
C 允许您在同一个声明中定义结构类型和声明该类型的对象。将这两个操作分开可能是有意义的:
struct book { char title[50]; int year; }; // creates the *type* "struct book"
struct book boo; // declares a *variable* of type "struct book"
typedef 工具允许您为类型创建同义词或别名 - 在这种情况下,typedef struct book { char title[50]; int year; } boo; 创建 boo 作为 struct book 的同义词。然后您可以将对象创建为
boo b1; // b1 is type boo, which is a synonym for struct book.
再一次,拆分可能会有所帮助:
struct book { char title[50]; int year; }; // creates the type "struct book"
typedef struct book boo; // makes boo an alias for type "struct book"
在struct book 中,book 是结构类型的标记名称 - 它允许您在定义后引用该类型,例如
struct book b2;
void some_function( struct book b );
等等
如果你写类似的东西
struct { char title[50]; int year; } boo;
然后只有 boo 可以有那个类型 - 你不能声明相同类型的其他变量,因为没有办法再引用它了。即使你重复输入:
struct { char title[50]; int year; } boo;
struct { char title[50]; int year; } b2;
boo 和 b2 在技术上具有不同的类型,即使类型实现相同。
现在,如果你使用 typedef 工具,你可以省略标签名:
typedef struct { char title[50]; int year } boo;
因为现在您使用 typedef 名称来引用该类型 boo:
boo b2;
void some_function( boo b );
【讨论】:
当标识符(名称)出现在struct 之后时,它被称为标签,struct 和标识符名称的组合称为类型。很简单,struct book 是一个类型;它的名字是struct book。
当标识符出现在结构声明的大括号之后时,它是一个单独的名称——它与结构没有直接联系。它的作用取决于它所在的更大的声明。要了解这一点,请考虑声明的一种形式是“type name ;”。例如,我们可以:
int a;
char b;
struct foo c;
struct bar { float x, y, z; } d;
在每一个中,a、b、c 和 d 是正在声明的对象的标识符,其前面的文本是类型名称。 struct foo 和 struct bar { float x, y, z } 只是复杂的类型名称,而不是单个单词。在声明标识符时,我们可以使用任何我们想要的名称(遵循关于使用哪些字符以及保留名称等的常规规则)。
我们还可以在类型名前加上各种修饰符,比如:
extern int a;
static char b;
const struct foo c;
typedef struct bar { float x, y, z; } d;
上面的前三个也声明了对象。第四,typedef 是特殊的。它说“这不是声明一个对象;它正在为一种类型命名。”第四个声明说“d”是struct bar 的新名称。
通常使用typedef 为与结构标记同名的struct 创建别名,如:
typedef struct bar { float x, y, z; } bar;
但是,在 C 中对此没有要求。结构的名称及其类型的任何别名都是不相关的,除非程序员编写了 typedef 使它们相同。 (在 C++ 中,这是自动完成的;声明 struct bar 会创建一个名为 bar 的类型。在 C 中,结构标记与类型名称位于不同的名称空间中。)
【讨论】: