• 预处理指令


    预处理器是一些指令,指示编译器在实际编译之前所需完成的预处理。

    所有的预处理器指令都是以井号(#)开头,只有空格字符可以出现在预处理指令之前。预处理指令不是 C++ 语句,所以它们不会以分号(;)结尾。

    我们已经看到,之前所有的实例中都有 #include 指令。这个宏用于把头文件包含到源文件中。

    C++ 还支持很多预处理指令,比如 #include、#define、#if、#else、#line 等,让我们一起看看这些重要指令。

    #define指令:#define 预处理指令用于创建符号常量。该符号常量通常称为,指令的一般形式是:#define macro-name replacement-text 

    1 #include <iostream>
    2 using namespace std;
    3 #define PI 3.14
    4 int main()
    5 {
    6     cout << PI << endl;
    7     return 0;
    8 }

    结果为:3.14

    也可以定义一个带参数的宏

    1 #include <iostream>
    2 using namespace std;
    3 #define sum(a,b) a+b
    4 int main()
    5 {
    6     cout << sum(1,2) << endl;
    7     return 0;
    8 }

    结果为:3

    条件编译:有几个指令可以用来有选择地对部分程序源代码进行编译。这个过程被称为条件编译。条件预处理器的结构与 if 选择结构很像。比如

    1 #define NULL
    2 #ifdef NULL
    3 #define NULL "Hello World !"
    4 #endif
    5 int main()
    6 {
    7     cout << NULL << endl;
    8     return 0;
    9 }

    结果为:hello wrold!  代码的意思是如果定义了NULL,就把他定义为helloworld。当然也可以变成如果没有定义#ifndef

     1 int main()
     2 {
     3     int a = 5;
     4 
     5     #if 0
     6     a = 8;
     7     #endif
     8     cout << a << endl;
     9     system("pause");
    10     return 0;
    11 }

    结果为:5   说明用#if 0  #endif 包括的代码不会被编译

    #和##运算符:这里在代码中他们两个都是运算符,而不是指令。

    1 #define a(x) #x
    2 int main()
    3 {
    4     cout << a(hello world) << endl;
    5     return 0;
    6 }

    结果为:helloworld 。这里的#x运算符会把a(x)转换为用引号引起来的字符串。相当于"hello world"。

    1 #define a(x,y) y##x
    2 int main()
    3 {
    4     int yx = 100;
    5     cout << a(x,y) << endl;
    6     return 0;
    7 }

    结果为:100。说明##的作用是用于连接两个令牌。

  • 相关阅读:
    Nodejs 进阶:Express 常用中间件 body-parser 实现解析
    Nodejs进阶:express+session实现简易身份认证
    Node 进阶:express 默认日志组件 morgan 从入门使用到源码剖析
    Nodejs进阶:如何玩转子进程(child_process)
    express+session实现简易身份认证
    你真的了解UIViewController生命周期吗?
    你真的了解UIGestureRecognizer吗?
    你真的了解UIEvent、UITouch吗?
    你真的了解UIScrollView吗?
    你真的了解UITextView吗?
  • 原文地址:https://www.cnblogs.com/xiaodangxiansheng/p/11120979.html
Copyright © 2020-2023  润新知