C语言宏控 # 和 ## 的用法

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$ 

*/
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值