C语言中#和##的用法

1. #的用法

在C语言中,#可以用来宏的转换成字符量,它仅允许出现在带参数的宏的替换列表中程序如下:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 
 4 #define str1(s) #s
 5 #define str2(s) "#s"
 6 #define str3(s) '#s'
 7 
 8 int
 9 main(void)
10 {
11     char *hello = "HELLO";
12     printf("%s = %s\n", str1(hello), hello);
13     printf("%s = %s\n", str2(hello), hello);
14     printf("%s = %s\n", str3(hello), hello);
15     return 0;
16 }

需要注意的是,在双括号("")和单括号('')中,它的特殊作用会被关闭。所以程序有警告和错误:

1 elvis@elvis:~/program/test$ gcc test_#.c 
2 test_#.c:14:35: warning: multi-character character constant
3 test_#.c: In function ‘main’:
4 test_#.c:14: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
5 elvis@elvis:~/program/test$ ./a.out 
6 hello = HELLO
7 #s = HELLO
8 Segmentation fault

2. ##的用法

##运算符可以将两个记号(例如标识符)“粘”在一起,成为一个记号。(无需惊讶,##运算符被称为“记号粘合”。)
如果其中一个操作数是宏参数,“粘合”会在当形式参数被相应的实际参数替换后发生。
 
posted @ 2012-10-21 21:42  leealways87  阅读(1198)  评论(0编辑  收藏  举报