c - 为什么#define 和 typedef 操作数是倒置的?

标签 c typedef c-preprocessor

以下定义 AB 替换:

#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/

相关文章:

可以在嵌套 for 循环中使用双括号吗?

c - 我的 Sublime Text 构建系统,在当前文件夹中运行 build.sh

c - C 中的函数 strtok() 和混合变量类型

c - typedef 一个结构在它被声明之前

c - 如何给MACRO加L前缀

在 C 中从多个 char 数组字段创建 int 值

c - C union 内的引用类型

c++ - 错误 : using typedef-name after class

c++ - Objective-C 预处理器定义,动态 C 字符串到 NSString 声明

c - 如何使用宏扩展作为编译指示的第一个标识符?