阅读耗时大概 1 分钟
define 预处理
#define macro-name replacement-text
我们常说的宏常量不就是这样写的么。 在程序编译前 会将 macro-name 替换成 我们定义的值
直接看代码吧
#include <iostream>using namespace std;#define PI 3.14159int main (){cout << "Value of PI :" << PI << endl;return 0;}输出结果是Value of PI :3.14159
参数宏
#include <iostream>using namespace std;#define MIN(a,b) (a<b ? a : b)int main (){int i, j;i = 60;j = 30;cout <<"较小的值为:" << MIN(i, j) << endl;return 0;}输出结果较小的值为: 30
条件编译
主要是利用几个指令来有选择地对部分程序源代码进行编译。和 if else 逻辑很像
只在调试时进行编译,调试开关可以使用一个宏来实现
//如果之前定义了符号常量debug#ifdef DEBUGcerr <<"Variable x = " << x << endl;#endif
注释代码
#if 0//不进行编译的代码#endif
#include <iostream>using namespace std;#define DEBUG#define MIN(a,b) (((a)<(b)) ? a : b)int main (){int i, j;i = 100;j = 30;#ifdef DEBUGcerr <<"Trace: Inside main function" << endl;#endif#if 0/* 这是注释部分 */cout << MKSTR(HELLO C++) << endl;#endifcout <<"The minimum is " << MIN(i, j) << endl;#ifdef DEBUGcerr <<"Trace: Coming out of main function" << endl;#endifreturn 0;}输出结果Trace: Inside main functionThe minimum is 30Trace: Coming out of main function
#和##运算符
#include <iostream>using namespace std;#define MKSTR( x ) #xint main (){//下面这句话 直接经过预处理器 转换成了 HELL C++cout << MKSTR(HELLO C++) << endl;return 0;}输出结果HELLO C++
##运算符用于连接两个参数令牌#define CONCAT( x, y ) x ## y
#include <iostream>using namespace std;#define concat(a, b) a ## bint main(){int xy = 100;//编译器预处理后变成了 xycout << concat(x, y);return 0;}输出结果100
预定义宏
| 宏 | 描述 |
|---|---|
| LINE | 会在程序编译时包含当前行号 |
| FILE | 会在程序编译时包含当前文件名 |
| DATE | 会包含一个形式为 month/day/year 的字符串,它表示把源文件转换为目标代码的日期 |
| TIME | 会包含一个形式为 hour:minute:second 的字符串,它表示程序被编译的时间 |
#include <iostream>using namespace std;int main (){cout << "Value of __LINE__ : " << __LINE__ << endl;cout << "Value of __FILE__ : " << __FILE__ << endl;cout << "Value of __DATE__ : " << __DATE__ << endl;cout << "Value of __TIME__ : " << __TIME__ << endl;return 0;}输出结果Value of __LINE__ : 6Value of __FILE__ : test_define.cppValue of __DATE__ : May 4 2022Value of __TIME__ : 20:01:19
