本身引用匿名结构
Referencing an anonymous struct in itself
typedef struct {
//
} list;
对
typedef struct list{
//
} list;
我在另一篇文章(例如Using an anonymous struct vs a named struct with typedef)中读到这两个几乎是等价的,唯一需要后者的情况是在引用结构本身时。
但是,下面的代码可以用 clang 和 gcc 编译:
#include <stdio.h>
typedef struct {
struct list *next;
} list;
int main(){
list l;
return 0;
}
上面我有一个引用自身的匿名结构。这是如何编译的?
首先,您的问题中既没有匿名结构。有未命名结构的例子。
匿名结构的概念在 C 标准中定义如下(6.7.2.1 结构和联合说明符)
13 An unnamed member of structure type with no tag is called an
anonymous structure; an unnamed member of union type with no tag is
called an anonymous union. The members of an anonymous structure or
union are considered to be members of the containing structure or
union. This applies recursively if the containing structure or union
is also anonymous.
至于这个声明
typedef struct {
struct list *next;
} list;
然后声明了两种不同的类型:具有别名 list
的未命名结构和类型 struct list
的不完整声明。 list
和 struct list
是两种不同的不兼容类型。
例如,如果您要尝试这个简单的程序
#include <stdio.h>
typedef struct {
struct list *next;
} list;
int main(void)
{
list lst1;
list lst2;
lst1.next = &lst2;
return 0;
}
那么编译器会针对这条语句报错
lst1.next = &lst2;
说有一个从不兼容的指针类型“list *”到“struct list *”的赋值。
typedef struct {
//
} list;
对
typedef struct list{
//
} list;
我在另一篇文章(例如Using an anonymous struct vs a named struct with typedef)中读到这两个几乎是等价的,唯一需要后者的情况是在引用结构本身时。
但是,下面的代码可以用 clang 和 gcc 编译:
#include <stdio.h>
typedef struct {
struct list *next;
} list;
int main(){
list l;
return 0;
}
上面我有一个引用自身的匿名结构。这是如何编译的?
首先,您的问题中既没有匿名结构。有未命名结构的例子。
匿名结构的概念在 C 标准中定义如下(6.7.2.1 结构和联合说明符)
13 An unnamed member of structure type with no tag is called an anonymous structure; an unnamed member of union type with no tag is called an anonymous union. The members of an anonymous structure or union are considered to be members of the containing structure or union. This applies recursively if the containing structure or union is also anonymous.
至于这个声明
typedef struct {
struct list *next;
} list;
然后声明了两种不同的类型:具有别名 list
的未命名结构和类型 struct list
的不完整声明。 list
和 struct list
是两种不同的不兼容类型。
例如,如果您要尝试这个简单的程序
#include <stdio.h>
typedef struct {
struct list *next;
} list;
int main(void)
{
list lst1;
list lst2;
lst1.next = &lst2;
return 0;
}
那么编译器会针对这条语句报错
lst1.next = &lst2;
说有一个从不兼容的指针类型“list *”到“struct list *”的赋值。