1、常见的宏定义语句有不带参数的宏定义和带参数的宏定义两种
2、带参数的宏定义,在比较复杂时,往往通过\字符进行换行分割,来使其更加清晰。
比如:
#include <stdio.h>
#include <string.h>
#define FUNC(a, b) \
printf("The add of "#a" and "#b" is %d\n", ((a)+(b)))
int main()
{
int m = 30;
int n = 20;
FUNC(m, n);
return 0;
}
3、#符号的作用
在宏定义语句中,该符号有特殊的作用,其功能相当于将宏参数格式化输出为字符串。在上述代码中,其最终的结果为:
The add of m and n is 50
注意:在使用该符号时,要在两边加双引号,这样才能得到预期的结果。
4、##符号的作用
在宏定义语句中该符号为宏连接符,用来连接变量名。
#include <stdio.h>
#include <string.h>
#define FUNC(a, b) \
printf("%d\n", a##b)
int main()
{
int m = 30;
int n = 20;
int mn = 50;
FUNC(m, n);
return 0;
}
在上述代码中,m和n被连接为mn,又因为mn已经被定义为了50,所以最后输出50。
5、关于可变参数宏
可变参数宏的调用形式,常有以下两种:
#define debug(...) printf( __VA_ARGS__)
#include <stdio.h>
#include <string.h>
#define debug(...) printf(__VA_ARGS__)
int main()
{
int m = 30;
debug("m is %d\n", m);
return 0;
}
输出结果通printf一致
#define debug(arg...) printf(arg) 这种表达形式同上述形式一致,相当于给宏可变参数起了个名字,但是这么写可读性更强并且更容易进行描述。
以上两种方式均跟具体的编译器相关。