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

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

我不知道是否typedef#define在同一个Ç



萧十郎
浏览 350回答 3
3回答

回首忆惘然

没有。#define是一个预处理器令牌:编译器本身永远不会看到它。typedef是一个编译器令牌:预处理器不关心它。您可以使用其中一种来达到相同的效果,但最好根据您的需要使用合适的效果#define MY_TYPE inttypedef 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 */

慕后森

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, ctypedef int a10[10];a10 a, b, c;  // create three 10-int arraystypedef int (*func_p) (int);func_p fp;  // func_p is a pointer to a function that            // takes an int and returns an int

湖上湖

不,他们不一样。例如:#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 intOBNOXIOUSFUNC anObnoxiousFunc; // anObnoxiousFunc is a pointer to a function                               // returning a pointer to a 20-element array                               // of pointers to int尝试使用预处理器宏执行此操作。
打开App,查看更多内容
随时随地看视频慕课网APP