预编译时宏替换 见解

在预编译的过程中  主要处理#  和宏替换

例如

#include<stdio.h>
#define  PI  3.14

int main(){

double  r=3, s;
s=r*r*PI;
printf("%f\n",s);
return 0;
}  

在预编译的时候   代码变成如下

#include<stdio.h>


int main(){

double  r=3, s;
s=r*r*3.14;
printf("%f\n",s);
return 0;
}  

#define  PI  3.14  不开辟空间  不要求类型  只将源码中所有的PI 替换成3.14

#include<stdio.h>
#define int int*
int main(){

int p;
return 0;
}

上面这段代码在预编译的时候将所有int  替换为int *    主函数返回类型为指针型   p为指针变量

宏定义带参时

#include<stdio.h>
#define SUM(x,y)(x*y)
int main(){
int a=3,b=4;
int c=SUM(a+5,b+6);
//预编译时替换为  int c=SUM(a+5*b+6)
printf("%d\n",c);
return 0;
}

输出  c=29

#include<stdio.h>
#define MAX (x,y)((x)>(y)?(x):(Y))
int main(){

int a=10,b=5;
MAX(++a,b);
printf("%d",a):
return 0;

输出  a=12;

猜你喜欢

转载自www.cnblogs.com/lc-bk/p/11069799.html