C语言中的宏定义(#define)
·
预处理器支持文本宏替换和类函数文本宏替换。
不带参数的宏
形式:#define identifier replacement-list
这是不带参数的宏,也叫 “对象式宏”,作用是做简单的文本替换。
例如:
#include <stdio.h>
#define INSTRUCTION_CACHE_ENABLE 1U
#define MY_MESSAGE "hello"
int main()
{
printf("%u\n", INSTRUCTION_CACHE_ENABLE);
printf("%s\n", MY_MESSAGE);
return 0;
}
运行输出:

带参数的 “类函数宏”
固定参数形式#define identifier ( parameters ) replacement-list
例如:
#include <stdio.h>
#define MAX(x,y) ((x) > (y) ? (x):(y))
int main()
{
printf("%d\n", MAX(1, 2));
printf("%d\n", MAX(200, 2));
return 0;
}
运行输出:

固定参数+可变参数形式#define identifier ( parameters, ... ) replacement-list
可变参数会被 __VA_ARGS__接收过来。
例如:
#include <stdio.h>
#define PRT(format, ...) printf(format, __VA_ARGS__)
int main()
{
PRT("hello %d\n", 1);
PRT("hello %d %s\n", 1, "good");
return 0;
}
运行输出:

纯可变参数形式#define identifier ( ... ) replacement-list
(…):参数列表只有一个 …,表示纯可变参数,可以接收任意数量的参数(包括 0 个)。
可变参数会被 __VA_ARGS__接收过来。
例如:
#include <stdio.h>
#define PRT(...) printf(__VA_ARGS__)
int main()
{
PRT("hello\n");
PRT("hello %d %s\n", 1, "good");
return 0;
}
运行输出:

更多推荐
所有评论(0)