以下定义 A
被 B
替换:
#define A B
虽然这将 A
定义为 type B
的别名:
typedef B A;
为什么?这不是语无伦次吗?
最佳答案
简单地说:考虑以下变量声明:
// declare a variable called "myInt" with type int
int myInt;
// declare a variable called "myDouble" with type double
double myDouble;
// declare a variable called "myLong" with type long
long myLong;
// declare a variable called "myFunc" with type pointer to function
void (*myFunc)(char*);
那么 typedef
就很有意义了:
// declare a type alias called "myInt" with type int
typedef int myInt;
// declare a type alias called "myDouble" with type double
typedef double myDouble;
// declare a type alias called "myLong" with type long
typedef long myLong;
// declare a type alias called "myFunc" with type pointer to function
typedef void (*myFunc)(char*);
另一方面,宏可以采用函数式语法:
#define A(B, C) B, C
A(1, 2) // expands out to 1, 2
所以对于宏来说,“名称”后面的“定义”更有意义。
(顺便说一句,这也适用于 C++。)
关于c - 为什么#define 和 typedef 操作数是倒置的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5135693/