【问题标题】:How does the compiler differentiate typedef struct implementation with the type having the same name as the structure?编译器如何区分 typedef struct 实现与与结构同名的类型?
【发布时间】:2020-05-12 00:26:09
【问题描述】:

我一直在研究单链表,并与两个不同的typedef struct 实现交叉。

1st(在CS50讲座讲解):

// Represents a node:

typedef struct node
{
    int number;
    struct node *next;
}
node;

第2名(在CS50短视频讲解):

typedef struct sllist
{
    int number;
    struct sllist *next;
}
sllnode;

我的问题是: 在前一个实现中,编译器如何区分node,别名和nodestruct? 为什么它能够区分structtypedef,但我不能使用相同的变量名来表示intstring,例如?

【问题讨论】:

  • 它们被放在不同的“命名空间”或“类别”中。
  • 一个是struct node,另一个是node,这将是同一件事,但*next;作为自引用成员node尚未定义,所以它有成为struct node
  • 虽然对于 C++(因此不是纯 C 和 存在差异),stackoverflow.com/a/612350/2864740 可能是一个不错的读物。它还包括指向 C 资源的链接。我无法很快找到关于 SO 的类似 C 特定答案,尽管应该可以使用它来搜索。

标签: c data-structures struct typedef cs50


【解决方案1】:

编译器如何区分节点、别名和节点、结构?

很简单:它们是两种不同的东西。一个前面有struct 关键字,一个没有。 typedef 可以看作是创建别名。如果编译器只看到node,它会查看typedef 以获取真正的类型,而如果它看到struct node,它已经知道类型。

为什么它可以区分struct和typedef,但是我不能使用相同的变量名来表示int和string,例如?

这是一个不同的场景。您不能重新定义已经存在的类型名称。你不能做typedef something int; 因为int 已经存在,就像你不能做一样:

struct s {
    int a;
};

struct s {
    int a;
};

这个单一定义规则也适用于变量名和函数名。

【讨论】:

    猜你喜欢
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-10
    相关资源
    最近更新 更多