C++ 预处理器

预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理,指令以 # 开头,不需要以分号;结尾。
预处理器主要是完成文本替换的操作

常见的预处理器

预处理器描述
#include导入头文件
#ifif判断操作,必须有#endif配对使用
#elif类似于 else if
#elseelse
#endif结束if
#define定义一个宏
#ifdef如果已经定义了一个宏
#ifndef如果还没有定义一个宏
#undef取消定义宏
#pragma设定编译器的状态

#define 宏变量

用于创建符号常量,称为宏。

#include <iostream>

#define NUMBER1 30
#define NUMBER2 "hello"
#define NUMBER3 30.222

int main() {
    int a = NUMBER1;            // 在实际编译之前,会被替换为 int a = 30; 
    std::string s = NUMBER2;    // 在实际编译之前,会被替换为 std::string s = "hello";  
    float f = NUMBER3;          // 在实际编译之前,会被替换为 float f = 30.222;  

    std::cout << a << std::endl;
    std::cout << s << std::endl;
    std::cout << f << std::endl;

    return 0;
}

#ifndef、#define

如果没有定义宏NUMBER
就进行定义宏NUMBER为30

#include <iostream>

#ifndef NUMBER
#define NUMBER 30
#endif

int main() {
    std::cout << NUMBER << std::endl;

    return 0;
}

#ifdef

#include <iostream>

#ifndef NUMBER1
#define NUMBER1 30
#endif

int main() {
#ifdef NUMBER
    std::cout << NUMBER << std::endl;
#else
    std::cout << "not define NUMBER!" << std::endl;
#endif

    return 0;
}

#if、#elif、#else、#endif

#include <iostream>

#ifndef NUMBER
#define NUMBER 30
#endif

int main() {
#if NUMBER <= 50
    std::cout << " <= 50" << std::endl;
#elif NUMBER <= 100
    std::cout << " <= 100" << std::endl;
#else
    std::cout << " > 100" << std::endl;
#endif

    return 0;
}

#undef

#include <iostream>

int main() {
#ifndef NUMBER
#define NUMBER 30
#endif

#ifdef NUMBER
    std::cout << NUMBER << std::endl;
#else
    std::cout << "not define NUMBER!" << std::endl;
#endif

#undef NUMBER

#ifdef NUMBER
    std::cout << NUMBER << std::endl;
#else
    std::cout << "not define NUMBER!" << std::endl;
#endif
    return 0;
}
// 结果:
// 30
// not define NUMBER!

宏函数

优点:文本替换,不会造成函数的调用开销(开辟栈空间,形参压栈,函数弹栈释放等)
缺点:会导致代码体积增加

#include <iostream>

#define TEST1(a) std::cout << a << std::endl;
#define TEST2(a, b) a + b
#define TEST3(a, b) a * b

int main() {
    TEST1(100); // 100

    int res = TEST2(1+1, 2+2);
    std::cout << res << std::endl; // 6

    int res2 = TEST3(1+1, 2+2);
    std::cout << res2 << std::endl; // 5
    // int res2 = TEST3(1+1, 2+2);
    // 被替换为:
    // int res2 = 1 + 1 * 2 + 2;  替换后,乘法优先了

    return 0;
}

预定义宏

#include <iostream>

int main() {
    std::cout << __DATE__ << std::endl; // Sep 24 2021
    std::cout << __TIME__ << std::endl; // 08:47:59
    std::cout << __TIMESTAMP__ << std::endl; // Fri Sep 24 08:47:54 2021

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值