C++宏#号的用法

1. #:在宏展开的时候会将#后面的参数替换成字符串,如:
#define p(exp) printf(#exp);
调用p(hello)的时候会将#exp换成”hello”

The # operator should not be confused with the null directive.

Use the # operator in a function-like macro definition according to the following rules:

[list]
[*]A parameter following # operator in a function-like macro is converted into a character string literal containing the argument passed to the macro.
[*]White-space characters that appear before or after the argument passed to the macro are deleted.
[*]Multiple white-space characters imbedded within the argument passed to the macro are replaced by a single space character.
[*]If the argument passed to the macro contains a string literal and if a \ (backslash) character appears within the literal, a second \ character is inserted before the original \ when the macro is expanded.
[*]If the argument passed to the macro contains a " (double quotation mark) character, a \ character is inserted before the " when the macro is expanded.
[*]The conversion of an argument into a string literal occurs before macro expansion on that argument.
[*]If more than one ## operator or # operator appears in the replacement list of a macro definition, the order of evaluation of the operators is not defined.
[*]If the result of the macro expansion is not a valid character string literal, the behavior is undefined.
[/list]

Example: # operator

The following examples demonstrate the use of the # operator:

#define STR(x) #x
#define XSTR(x) STR(x)
#define ONE 1

[table]
|Invocation |Result of Macro Expansion|
|STR(\n "\n" '\n') |"\n \"\\n\" '\\n'"|
|STR(ONE) |"ONE"|
|XSTR(ONE) |"1"|
|XSTR("hello") |"\"hello\""|
[/table]


2. ##:将前后两个的单词拼接在一起。例如《The C Programming Language》中的例子:
#define cat(x,y) x##y
调用cat(var, 123)展开后成为var123.
3. #@:将值序列变为一个字符
#define ch(c) #@c
调用ch(a)展开后成为’a’.


ref:
http://publib.boulder.ibm.com/infocenter/iadthelp/v7r0/index.jsp?topic=/com.ibm.etools.iseries.langref.doc/ilcrefer17.htm
http://www.trueeyu.com/?p=505

[color=white]作者:翁志艺[/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值