7. 预处理器

1. 不容忽视宏定义中的空格

#define f (x) ((x)-1)
#define f(x) ((x)-1)

这两个宏是不同的

2. 宏并不是函数

由于宏知识预处理器进行简单的字符串替换,替换后会增加代码的体积,和该语言中所定义的函数不同。

在C语言中使用宏进行写代码时为

#include<iostream>

using namespace std;

#define max(x, y) ((x) > (y) ? (x) : (y))

int main(){
    int i = 0, y = 1;
    int k = max(i, y);

    int j = max(i++, y++);
    reutrn 0;
}

  经预处理后,代码为

#以上部分进行省略
# 2 "1.cpp" 2


# 3 "1.cpp"
using namespace std;



int main(){
    int i = 0, y = 1;
    int k = ((i) > (y) ? (i) : (y));

    int j = ((i++) > (y++) ? (i++) : (y++));
    reutrn 0;
} 

3.宏并不是语句

在进行编写代码时,应该时刻想着替换后的代码为什么样子,宏替换过程中并不等同于语句

使用宏定义进行编写代码为

#include<iostream>
using namespace std;
#define condition(x) 
    if(x) cout<<"yes"<<endl;
int main(){
    int k = 1, y = 3;
    if(y)
        condition(k)
    else 
        cout<<"no condition"<<endl;
    reutrn 0;
}

预处理过后

# 2 "1.cpp" 2
# 3 "1.cpp"
using namespace std;

int main(){
    int k = 1, y = 3;
    if(y)
        if(k) cout<<"yes"<<endl;
    else
        cout<<"no condition"<<endl;
    reutrn 0;
}

进行缩进处理为

# 2 "1.cpp" 2
# 3 "1.cpp"
using namespace std;

int main(){
    int k = 1, y = 3;
    if(y)
        if(k)
            cout<<"yes"<<endl;
        else
            cout<<"no condition"<<endl;
    reutrn 0;
}    

发现和我们预想的方式不同

4. 宏不是定义

#include<iostream>
using namespace std;
#define ll_ptr long long * 
int main(){
    ll_ptr k, l;
    return 0;
}

  经转换后为

# 2 "1.cpp" 2
# 3 "1.cpp"
using namespace std;
int main(){
    long long * k, l;
    return 0;
} 

  可以看出

转换后,k为指向long long的指针,而l为long long类型的变量

对于该功能我们应该使用

typedef long long * ll_ptr;

来为类型取别名。

原文地址:https://www.cnblogs.com/hebust-fengyu/p/12055991.html