为了账号安全,请及时绑定邮箱和手机立即绑定

c中的typedef和#define是否相同?

c中的typedef和#define是否相同?

C
萧十郎 2019-08-06 14:35:38
c中的typedef和#define是否相同?我不知道是否typedef和#define在同一个Ç?
查看完整描述

3 回答

?
回首忆惘然

TA贡献1847条经验 获得超11个赞

没有。


#define是一个预处理器令牌:编译器本身永远不会看到它。

typedef是一个编译器令牌:预处理器不关心它。


您可以使用其中一种来达到相同的效果,但最好根据您的需要使用合适的效果


#define MY_TYPE int

typedef int My_Type;

当事情变得“毛茸茸”时,使用正确的工具使其正确


#define FX_TYPE void (*)(int)

typedef void (*stdfx)(int);


void fx_typ(stdfx fx); /* ok */

void fx_def(FX_TYPE fx); /* error */


查看完整回答
反对 回复 2019-08-06
?
慕后森

TA贡献1802条经验 获得超5个赞

typedef遵守范围规则就像变量一样,而define保持有效直到编译单元结束(或直到匹配undef)。


此外,有些事情可以通过无法完成的事情typedef来完成define。

例如:


typedef int* int_p1;

int_p1 a, b, c;  // a, b, c are all int pointers


#define int_p2 int*

int_p2 a, b, c;  // only the first is a pointer, because int_p2

                 // is replaced with int*, producing: int* a, b, c

                 // which should be read as: int *a, b, c

typedef int a10[10];

a10 a, b, c;  // create three 10-int arrays

typedef int (*func_p) (int);

func_p fp;  // func_p is a pointer to a function that

            // takes an int and returns an int


查看完整回答
反对 回复 2019-08-06
?
湖上湖

TA贡献2003条经验 获得超2个赞

不,他们不一样。例如:


#define INTPTR int*

...

INTPTR a, b;

在预处理之后,该行扩展为


int* a, b;

希望你看到问题; 只会a有类型int *; b将被声明为plain int(因为*它与声明符相关联,而不是类型说明符)。


与之形成鲜明对比


typedef int *INTPTR;

...

INTPTR a, b;

在这种情况下,无论是a和b将有类型int *。


有些类型的typedef无法使用预处理器宏进行模拟,例如指向函数或数组的指针:


typedef int (*CALLBACK)(void);

typedef int *(*(*OBNOXIOUSFUNC)(void))[20]; 

...

CALLBACK aCallbackFunc;        // aCallbackFunc is a pointer to a function 

                               // returning int

OBNOXIOUSFUNC anObnoxiousFunc; // anObnoxiousFunc is a pointer to a function

                               // returning a pointer to a 20-element array

                               // of pointers to int

尝试使用预处理器宏执行此操作。


查看完整回答
反对 回复 2019-08-06
  • 3 回答
  • 0 关注
  • 349 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号