#if、#ifndef 和 #ifdef

发布时间 2023-07-06 13:42:56作者: luckilzy

1 简介

#ifndef 和 #ifdef 是一种宏定义判断,作用是防止多重定义。#ifndef 是 if not define 的简写,#ifdef 是 if define 的简写。

使用格式如下:

#if #ifdef #ifndef
#if(判断条件)
程序段1
#else
程序段2
#endif
#ifdef(标识符)
程序段1
#else
程序段2
#endif
#ifndef(标识符)
程序段1
#else
程序段2
#endif

如果判断条件为真(假)或者定义了(没有定义)标识符,那么这个相应的程序段1(程序段2)就会被编译,否则就不会被编译。不同于 if-else 语句,if-else 语句都会被编译,但是会依据判断条件来决定是否执行相应的语句。

2 使用场景

(1)在头文件中使用,防止头文件被多重调用
(2)作为测试使用,省去注释代码的麻烦
(3)作为不同角色或场景的判断使用

2.1 头文件中使用

点击查看代码
/* header.h */
#ifndef HEADER_H_
#define HEADER_H_

#include "c_file.c"

class calssName
{
public:
    /* ...... */
private:
    /* ...... */
};

#endif

即使 c_file.c 文件中也包含了 header.h 头文件,由于 HEADER_H_ 的宏的存在,不会出现重复引用头文件,可以避免重复声明。

2.2 测试使用

点击查看代码
include <iostream>

#define IOI

using namespace std;

int main()
{
#ifdef IOI
    cout << "999" << endl;
#endif
    return 0;
}

可以通过是否注释 #define IOI 来控制主函数中的代码执行与否。

2.3 作为不同角色或者场景的判断使用

点击查看代码
#include <iostream>

using namespace std;

#define ADMIN 8

int main()
{
#if (ADMIN == 9)
    cout << "999" << endl;  /* 没有编译该语句 */
#else
    cout << "888" << endl;  /* 编译并执行了该语句 */
#endif
    return 0;
}