对 #define 和 typedef 感到困惑
#define T Stack_T
typedef struct T *T;
那么struct T
中的T
是什么意思,是由#define还是typedef
定义的呢?
#define T Stack_T
typedef struct T *T;
Then what does T
in struct T
mean,the one defined by #define
or typedef
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
#define
指令在编译过程的早期被替换(翻译阶段 4,编译实际上直到阶段 7 才发生,这些阶段以及期间发生的情况在标准第 5.1.1.2 节中有详细说明) )。#define
只会将T
预处理标记更改为Stack_T
。对
typedef
的影响将把它变成:接下来,
Stack_T
被定义为一个类型,一个指向另一个类型的指针struct Stack_T
的。 Stack_T 和 struct Stack_T 是两个独立的东西。#define
directives are substituted early on in the compilation process (translation phase 4, compilation doesn't actually occur until phase 7, these phases and what happens during them are detailed in the standard, section 5.1.1.2).That
#define
will simply changeT
pre-processing tokens intoStack_T
.The effect of that on the
typedef
will be to turn it into:Following that,
Stack_T
is defined as a type, a pointer to another type ofstruct Stack_T
. TheStack_T
andstruct Stack_T
are two separate things.预处理器只进行文本替换,因此代码看起来像这样
,所以代码中的每个
T
首先被替换为Stack_T
,之后编译器启动,看到typedef
并使用struct Stack_T*
。最好知道
struct Type
和Type
仅在 C++ 中相同,而在 C 中则不然。The preprocessor does only do text-substitutions, so that code would look like
So every
T
in your code is first replaced toStack_T
, and after that your compiler kicks in, sees thetypedef
and usesstruct Stack_T*
.It might be good to know that
struct Type
andType
are only the same in C++, not in C.由于
#define
在预编译中处理,而struct
在编译中处理,因此预编译后您将得到typedef struct T *T;
看起来像这样:typedef struct Stack_T *Stack_T;
Since
#define
is processed in pre-compilation andstruct
in compilation, after the pre-compilation you'll havetypedef struct T *T;
looks like that:typedef struct Stack_T *Stack_T;
T
代表Stack_T
,因此,您可以将 typedef 读作:因此代码中的每个
T
都会替换为Stack_T
> 在编译器编译期间。The
T
representsStack_T
so, you can read the typedef as:so every
T
in your code is replaced asStack_T
during compiler compilation.