转自:http://www.geeksforgeeks.org/write-a-c-macro-printx-which-prints-x/
http://www.geeksforgeeks.org/interesting-facts-preprocessors-c/
Macro是在preprocessor时的字符串替换,一切与compiler无关,缺点是当你debug的时候你会觉得莫名其妙。因为compiler看不到macro。
例子1. 首先看一个最普通的Macro
#include<stdio.h>
#define max 100
int
main()
{
printf
(
"max is %d"
, max);
return
0;
}
// Output: max is 100
// Note that the max inside "" is not replaced
例子2. macro函数
#include <stdio.h>
#define INCREMENT(x) ++x
int
main()
{
char
*ptr =
"GeeksQuiz"
;
int
x = 10;
printf
(
"%s "
, INCREMENT(ptr));
printf
(
"%d"
, INCREMENT(x));
return
0;
}
// Output: eeksQuiz 11
例子3. token##,用来连接参数
#include <stdio.h>
#define merge(a, b) a##b
int
main()
{
printf
(
"%d "
, merge(12, 34));
}
// Output: 1234
|
这里面相当于把12,34做字符串链接,然后原封不动的返回1234,不管类型。比如下面:
#include <stdio.h>
#define merge(a, b) a##b
int
main()
{
printf
(
"%d "
, merge(ab, 12));//报错,因为没有变量ab12,如果在前面定义int ab12 = 5;则会输出5;
}
// Output: 1234
例子4. token #用来转换成字符串
#include <stdio.h>
#define get(a) #a
int
main()
{
// GeeksQuiz is changed to "GeeksQuiz"
printf
(
"%s"
, get(GeeksQuiz));
}
// Output: GeeksQuiz
|
但是如果这样改
#include <stdio.h>
#define get(a) "a"
int
main()
{
// GeeksQuiz is changed to "GeeksQuiz"
printf
(
"%s"
, get(GeeksQuiz));
}
// Output: GeeksQuiz
这样无论传入什么参数给get,都只会输出"a",因为" "里面的内容是被当作字符串处理,不会替换
例子5.macro换行的时候用\代替
#include <stdio.h>
#define PRINT(i, limit) while (i < limit) \
{ \
printf
(
"GeeksQuiz "
); \
i++; \
}
int
main()
{
int
i = 0;
PRINT(i, 3);
return
0;
}
// Output: GeeksQuiz GeeksQuiz GeeksQuiz
|
例子6. 一些系统自带的Macro
11) There are some standard macros which can be used to print program file (__FILE__), Date of compilation (__DATE__), Time of compilation (__TIME__) and Line Number in C code (__LINE__)
例子7