找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 223|回复: 1

Question1.13:What's the difference between using a typedef or a #define for a user-defined type?

[复制链接]

210

主题

371

回帖

0

积分

管理员

积分
0
发表于 2013-7-13 15:23:08 | 显示全部楼层 |阅读模式
Q: What's the difference between using a typedef or a #define for a user-defined type?
A: In general, typedefs are preferred, in part because they can correctly encode pointer types. For example, consider these declarations:
                 typedef char *String_t;
                  #define String_d char *
                  String_t s1, s2;
                  String_d s3, s4;
s1, s2, and s3 are all declared as char *, but s4 is declared as a char, which is probably not the intention. (See also question 1.5.)
#defines do have the advantage that #ifdef works on them (see also question 10.15). On the other hand, typedefs have the advantage that they obey scope rules (that is,they can be declared local to a function or block).
See also questions 1.17, 2.22, 11.11, and 15.11.

210

主题

371

回帖

0

积分

管理员

积分
0
 楼主| 发表于 2013-7-13 18:30:39 | 显示全部楼层
问题:用typedef和#define作为用户定义类型的时候有什么区别?
回答:通常,用typedefs更好一点,部分原因就是它能够正确的编码指针类型。例如:
          typedef char *String_t;
                  #define String_d char *
                  String_t s1, s2;
                  String_d s3, s4;
s1、s2和s3都别声明为char *类型,但是s4仅仅只是一个char类型的,而这并不是我的意图(参考问题1.5)。
(注意:#define是预编译时起作用的,即字符替换。所以这里的String_d s3, s4;为char * s3,s4。所以这就与我在问题1.5中描述的情况是一样的了,这也是为什么s4是char型的原因了。typedef则是在编译的时候起作用的,它不仅仅是做字符替换这么简单,而是对变量的一种声明的方式。所以这里的s1跟s2都是char *类型的。)
#define有一个优势就是#ifdef作用于它的时候(参考问题10.15)。另一方面,typedef有一个优势就是它遵循作用域的规则(也就是说它可以在一个函数或者块内声明局部变量)。
注意:关于它们的作用域是有区别的。#define则跟函数是没有关系的,它是从定义开始直到文件结尾。那么作用域则是不会随函数的结束而结束。而typedef则不同,如果是在函数的外面,那么作用于则是从定义开始直到文件尾部。如果是在函数内部,则是从定义开始到函数结束的时候,那么它也会随函数的结束而结束。这也是typedef的作用的优势。)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

果子博客
扫码关注微信公众号

Archiver|手机版|小黑屋|风叶林

GMT+8, 2026-2-1 14:00 , Processed in 0.075068 second(s), 20 queries .

Powered by 风叶林

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表