Cpp的预处理Preprocessor-笔记

Cpp的Preprocessor

本文参考此处

预处理指示器(Preprocessor directives)不是C++语句,所以不用分号 “;” 结尾。

#define

  • 无参宏
  • 有参宏

条件编译

#if [defined()] / #ifdef / #ifndef
    ...
#endif

###

  • #:字符串化stringizing,Creating Strings from Macro Arguments

例子1:

#define PSQR(x) cout << "The square of x is:" << (x)*(x) << endl

PSQR(3);

// 运行结果:
The square of x is:9  // 结果,这里的x被当作普通文本对待,而不是可替换的token

例子2,修改后:

// 下面的 #x 将宏参数x转换成字符串"x"
#define PSQR(x) cout << "The square of " #x " is:" << (x)*(x) << endl

PSQR(3);

// 运行结果
The square of 3 is:9  //结果,将参数的数字3字符串化
  • ##:连接两个记号成为一个记号(combines two tokens into a single token
#define SAY1(x) A##x
#define SAY2(x,y) x##y
#define SAY3(x,y,z) x##y##z
#define SAY_XN(x,n) cout << #x#n " is:" << x##n <<endl

int A4 = 10;
int ab = 30;
int abc = 100;
cout << SAY1(4) << endl;        // 等价于 cout << A4 << endl;
cout << SAY2(a, b) << endl;     // 等价于 cout << ab << endl;
cout << SAY3(a, b, c) << endl;  // 等价于 cout << abc << endl;
SAY_XN(A, 4);

// 运行结果:
10
30
100
A4 is:10  // 单#和双#的使用

几个已定义的Macro

描述
__LINE__当前源代码行号
__FILE__源文件名
__DATE__日期:month day year
__TIME__时间:hour:minute:second

*The values of the predefined macros (except for __LINE__ and __FILE__) remain constant throughout the translation unit.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值