gpt4 book ai didi

c - C类型语法如何避免循环定义?

转载 作者:太空宇宙 更新时间:2023-11-04 00:20:07 24 4
gpt4 key购买 nike

此语句和示例来自Essential C by Nick Parlante.

C 类型语法的一个优点是它避免了循环定义问题,当指针结构需要引用自身时会出现这种问题。下面的定义定义了链表中的一个节点。请注意,无需预先声明节点指针类型。

   struct node {
int data;
struct node* next;
};

struct node* 仍在结构节点中时,C 编译器如何知道它是什么。

还有一个循环定义的例子,其中一个类型struct treenode*在被进一步定义之前使用。

typedef struct treenode* Tree;
struct treenode {
int data;
Tree smaller, larger; // equivalently, this line could say
// "struct treenode *smaller, *larger"
};

struct treenode* 尚未定义时,C 编译器如何知道它是什么。

相关问题:How does C resolve circular definition when a pointer in struct points to the struct itself? (这是相关的,它没有回答“如何”的问题)。

编辑:我假设 C 编译器能够一次完成此操作。

最佳答案

C标准规定在§6.2.5 Types ¶28 (强调):

A pointer to void shall have the same representation and alignment requirements as a pointer to a character type.48) Similarly, pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements. All pointers to structure types shall have the same representation and alignment requirements as each other. All pointers to union types shall have the same representation and alignment requirements as each other. Pointers to other types need not have the same representation or alignment requirements.

因此,C 编译器知道如何处理任何结构指针类型,因为所有结构指针必须具有相同的表示和对齐要求。无论您嵌入的是 struct node * 还是 struct value *,这都适用——无论编译器之前是否知道 struct value 类型。这也有助于“不透明类型”——您可以拥有指向编译器不知道结构内容的结构类型的指针。

您不能做的是在 struct node 的定义中嵌入一个 struct node(而不是 struct node *)。您可以将以前已知的结构类型作为值嵌入到结构中。您还可以在另一个结构类型中定义一个结构类型:

struct node
{
int data;
struct node *next;
struct key_value
{
int key;
char *value;
} kv;
};

与 C++ 不同,struct key_value 类型可用时没有范围问题 — 它不限于在 struct node 类型中使用。这不是好的编码习惯,但它是允许的。

关于c - C类型语法如何避免循环定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51345239/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com