C++ #ifndef

C++ #ifndef教程

C++#ifndef 用于判断,如果一个标识符没有被 #define 命令定义过,那么就编译该段代码,否则不编译。同时,#ifndef 还可以配合 #else 一起使用。

C++ #ifndef详解

语法

#ifndef identity code1 #endif

说明

如果标识符 identity 未被定义过,那么就编译代码 code1,否则就不编译。

语法

#ifndef identity code1 #else code2 #endif

说明

#ifndef 也可以配合 #else 一起使用,这里说明,如果标识符 identity 未被定义过,那么就编译代码 code1,否则就编译代码 code2。

案例

C++ #ifndef

使用 #ifndef 条件编译,执行编译代码

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; #ifndef PRINT cout << "Print not defined" << endl; #endif return 0; }

程序运行后,控制台输出如下图所示:

23_C ifndef.png

我们首先使用了 #ifndef 来判断宏 PRINT 是否已经定义,如果未被定义,则执行 cout 对应的代码,因为,我们的代码没有定义该宏,所以 cout 代码被执行。现在,我们修改程序如下:

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; #define PRINT #ifndef PRINT cout << "Print not defined" << endl; #endif return 0; }

程序运行后,控制台输出如下图所示:

24_C ifndef.png

这次,我们使用了 #define 定义了 PRINT 宏,此时,再次执行该程序,程序未执行 cout 代码。

C++ #ifndef

使用 #ifndef#else 执行不同的编译代码

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; #ifndef PRINT cout << "Print not defined" << endl; #else cout << "Print has defined" << endl; #endif return 0; }

程序运行后,控制台输出如下图所示:

25_C ifndef.png

我们首先使用了 #ifndef 来判断宏 PRINT 是否已经定义,如果未被定义,则执行第一个 cout 对应的代码,如果定义了,那么就执行第二个 cout 代码。

因为,我们的代码没有定义该宏,所以执行了第一个 cout 代码。现在,我们修改程序如下:

#include <iostream> using namespace std; int main() { cout << "嗨客网(www.haicoder.net)\n" << endl; #define PRINT #ifndef PRINT cout << "Print not defined" << endl; #else cout << "Print has defined" << endl; #endif return 0; }

程序运行后,控制台输出如下图所示:

26_C ifndef.png

这次,我们使用了 #define 定义了 PRINT 宏,此时,再次执行该程序,程序执行了第二个 cout 代码。因此,我们使用了 #ifndef#else 实现了控制不同的代码编译逻辑。

C++ #ifndef教程总结

C++ 的 #ifndef 用于判断,如果一个标识符没有被 #define 命令定义过,那么就编译该段代码,否则不编译。同时,#ifndef 还可以配合 #else 一起使用。