C/C++: 预处理指令

来源:互联网 发布:burpsuite使用教程知乎 编辑:程序博客网 时间:2024/05/16 09:49

C/C++: 预处理指令

标签: C/C++ 预处理指令

by 小威威


今天我来简要地总结一下预处理指令。众所周知,预处理指令可用于文件包含,宏定义与条件编译。
文件包含的关键字就是: #include
宏定义的关键字是: #define
条件编译的关键字是: #if #ifdef #ifndef #else #endif

对于文件包含,我觉得我就不用多解释了,相信大家非常熟悉。

宏定义,也就是#define,主要有两种用法: 第一:符号常量,也就是宏; 第二:带参数的宏。
符号常量:

#define PI 3.14159

带参数的宏:

# include <iostream>#define MIN(a,b) ((a < b) ? a : b)using namespace std;int main(void) {    int i = 10;    int j = 12;    cout << "The mixest one is :" << MIN(i,j) << endl;    return 0;}

此处,我重点要强调的就是条件编译,就如上文提到,条件编译的关键字有:#if #else #ifdef # ifndef #endif。
那么,这几个关键字有什么作用,有什么区别呢?
其实,条件编译的一个很大的用处就是用于debug,即将条件编译作为代码调试的开关。

# if 条件    代码# endif

如果满足这个条件,就将代码插入到源文件对应的位置;

# ifdef 字符常量    代码# endif# ifndef 字符常量    代码# endif

ifdef表示如果在前面有定义字符常量,就执行代码
同理,ifndef表示如果在前面没有定义字符常量,就执行代码

下面展示一个例子:

# include <iostream># define SWIFT 1# define DEBUGusing namespace std;int main(void) {    cout << "Hello, world!" << endl;    #ifdef DEBUG        cout << "You are using #ifdef" << endl;        cout << "The program has found the key 'DEBUG'" << endl;    #endif    #ifndef DEBUG        cout << "You are using #ifndef" << endl;        cout << "The program has not found the key 'DEBUG'" << endl;    #endif    #if SWIFT        cout << "You are using #if" << endl;    #endif    return 0;}输出结果:Hello, world!You are using #ifdefThe program has found the key 'DEBUG'You are using #if

倘若我讲SWIFT后的数字改为 0,那么这段代码便不会被编译,这个可以应用到调试!作为调试的开关!
倘若我把# define DEBUG这个语句删去,那么便会执行#ifndef里的内容。

总之,条件编译应用于代码调试是非常方便的,它省去了重复添加,删除的麻烦!


以上内容皆为本人观点,欢迎大家提出批评和指导,我们一起探讨!


0 0
原创粉丝点击