C Language Study - how to use '#'
来源:互联网 发布:淘宝旅行日历js插件 编辑:程序博客网 时间:2024/04/25 09:59
Not use '#':
#define SQR(x) printf("The square of x is %d.\n",((x)*(x)));
SQR(8);
The square of x is 64.
Use '#':
#define SQR(x) printf("The square of "#x" is %d.\n",((x)*(x)));
SQR(8);
The square of 8 is 64.
宏中的#的功能是将其后面的宏参数进行字符串化操作(Stringizing operator),简单说就是在它引用的宏变量的左右各加上一个双引号。
如定义好#define STRING(x) #x之后,下面二条语句就等价。
char *pChar = "hello";
char *pChar = STRING(hello);
还有一个#@是加单引号(Charizing Operator)
#define makechar(x) #@x
char ch = makechar(b);与char ch = 'b';等价。
但有小问题要注意,宏中遇到#或##时就不会再展开宏中嵌套的宏了。什么意思了?比如使用char *pChar =STRING(__FILE__);虽然__FILE__本身也是一个宏,但编译器不会展开它,所以pChar将指向"__FILE__"而不是你要想的形如"D:\XXX.cpp"的源文件名称。因此要加一个中间转换宏,先将__FILE__解析成"D:\XXX.cpp"字符串。
定义如下所示二个宏:
#define _STRING(x) #x
#define STRING(x) _STRING(x)
再调用下面语句将输出带""的源文件路径
char* pChar = STRING(__FILE__);
printf("%s %s\n", pChar, __FILE__);
可以比较下STRING(__FILE__)与__FILE__的不同,前将带双引号,后一个没有双引号。
本文参考:
- C Language Study - how to use '#'
- lua study -- how to call lua function use C language
- How To Study C Programming Language
- How to study foreign language
- C Language Study - the use of symbol '##'
- How to use C programing language in Linux as a expert[ZT]
- How to study C && ASM Code(1)
- How to study C && ASM Code(2)
- How to study C && ASM Code(3)
- How to study C && ASM Code(6)
- How to study C && ASM Code(4)
- C Language Study - #error
- C Language Study - static
- How To Use the C Run-Time
- How to Use C's volatile Keyword
- How to Use C's volatile Keyword
- How to Use C's volatile Keyword
- how to use linux epoll with c
- Linux find命令
- cordova(phonegap)4.2自定义插件
- Arrays.toList
- Sicily 1137. 河床
- Java中变量存储位置的区别
- C Language Study - how to use '#'
- 离散事件模拟
- ServletContext的功能
- 《C井重游》
- POJ 3984 || 迷宫问题 (bfs
- Tracking相关的文章
- 黑马程序员——abstract和interface的区别
- C++ Primer学习总结 第3章 字符串,向量和数组
- hdu 5178 pairs