1,使用#把宏参数变为一个字符串,用##把两个宏参数贴合在一起.
#include<limits.h>
#define STR(s) #s
#define INT(a,b) a##b
int main()
{
printf(STR(vck)); //
printf("\n%d\n", INT(2,3)); //
return 0;
}
/*
book@www.100ask.org:~/Test$ gcc 13.c
book@www.100ask.org:~/Test$ ./a.out
vck
23
book@www.100ask.org:~/Test$
*/
#include<cstdio>
#include<climits>
#define STR(s) #s
#define CONS(a,b) int(a##e##b)
int main()
{
printf(STR(vck)); // 输出字符串"vck"
printf("%d\n", CONS(2,3)); // 2e3 输出:2000
return 0;
}
/*
book@www.100ask.org:~/Test$ g++ 13.c
book@www.100ask.org:~/Test$ ./a.out
vck2000
book@www.100ask.org:~/Test$
*/
2,当宏参数是另一个宏的时候 ,需要注意的是凡宏定义里有用’#‘或’##'的地方宏参数是不会再展开.
#include<stdio.h>
#include<limits.h>
#define STR(s) #s
int main()
{
printf("int max: %s\n", STR(INT_MAX)); // INT_MAX #include<climits>
return 0;
}
/*
book@www.100ask.org:~/Test$ gcc 13.c
book@www.100ask.org:~/Test$ ./a.out
int max: INT_MAX
book@www.100ask.org:~/Test$
*/
#include<cstdio>
#include<climits>
#define A (2)
#define CONS(a,b) int(a##e##b)
int main()
{
//这一行则是: printf("%s\n", int(AeA));
printf("%s\n", CONS(A, A)); // compile error
return 0;
}
/*
book@www.100ask.org:~/Test$
book@www.100ask.org:~/Test$ g++ 13.c
13.c: In function ‘int main()’:
13.c:8:25: error: ‘AeA’ was not declared in this scope
printf("%s\n", CONS(A, A)); // compile error
^
13.c:4:24: note: in definition of macro ‘CONS’
#define CONS(a,b) int(a##e##b)
^
book@www.100ask.org:~/Test$
*/
INT_MAX和A都不会再被展开, 然而解决这个问题的方法很简单. 加多一层中间转换宏. 加这层宏的用意是把所有宏的参数在这层里全部展开, 那么在转换宏里的那一个宏(_STR)就能得到正确的宏参数.
#include<cstdio>
#include<climits>
//#define A (2)//error
#define A 2
#define _STR(s) #s
#define STR(s) _STR(s)
#define _CONS(a,b) int(a##e##b)
#define CONS(a,b) _CONS(a,b)
int main()
{
// INT_MAX,int型的最大值0x7fffffff,为一个变量 #include<climits>
//STR(INT_MAX) --> _STR(0x7fffffff) 然后再转换成字符串;
printf("int max: %s\n",STR(INT_MAX));
//CONS(A, A) --> _CONS((2), (2)) --> int((2)e(2))
//printf("%d\n",CONS(A,A));
printf("%d\n",CONS(A,A));
return 0;
}
/*
book@www.100ask.org:~/Test$ g++ 13.c
book@www.100ask.org:~/Test$ ./a.out
int max: 0x7fffffff
200
book@www.100ask.org:~/Test$
*/