这里说一下define在使用时用出现的一些问题,是我在写题的时候遇到的。
一般情况下都是使用define定义的常数,比如说
#define inf 999999999
#define INF 0x3f3f3f
const int inf=99999999;
当然这里不如const 定义的时候更严密,因为const说明了变量的类型。
还有就是我们利用define函数的时候,也就是带参数的宏。比如#define max(a,b) a>b?a:b
就十分容易出现错误的包括机器和人理解上的错误。所以我们在使用的时候尽量在每一层次的时候都加一个扩号避免错误带来的麻烦。
#define Add(a,b) a+b.
c * Add(a,b) * d
得应该是c*(a+b)*d
, 然而机器读的时候就是c*a+b*d
.
我的理解就是说define 宏定义的函数这里的"(“和”)"不再是优先级运算符了。不能再代表小括号的。其他的可以看看下面代码的具体实例,自己写一下的,加深一下自己的理解。
#include <stdio.h>
#include <stdlib.h>
#define ADD(x) x+x
#define add(x) (x)+(x)
#define MAX(a,b) a>b?a:b
#define max(a,b) ((a)>(b)?(a):(b))
int main()
{
int m=7,n=2,k=100;
int ans0=ADD(n+m)*k; //n+m+n+m*k=2+7+2+7*100
int ans1=ADD(m+n)*k; //m+n+m+n*k=7+2+7+2*100
int ans2=add(n+m)*k; //n+m+(n+m)*k
int ans3=add(m+n)*k; //m+n+(m+n)*k
int ans4=(add(m+n))*k; //(m+n)*2*k
printf("ans0 = %d\n",ans0); // ans0 = 711 ;
printf("ans1 = %d\n",ans1); // ans1 = 216 ;
printf("ans2 = %d\n",ans2); // ans2 = 909 ;
printf("ans3 = %d\n",ans3); // ans3 = 909 ;
printf("ans4 = %d\n",ans4); // ans4 = 1800 ;
int max0=MAX(n,m)+k; //n>m?n:m+k n>m显示n,否则显示m+k
int max1=MAX(m,n)+k; //m>n?m:n+k
int max2=max(n,m)+k; //max(n,m)+k
int max3=max(m,n)+k; //max(n,m)+k
int max4=(max(m,n))+k;
printf("max0 = %d\n",max0); // max0 = 107 ;
printf("max1 = %d\n",max1); // max1 = 7 ;
printf("max2 = %d\n",max2); // max2 = 107 ;
printf("max3 = %d\n",max3); // max3 = 107 ;
printf("max4 = %d\n",max4); // ans3 = 107 ;
//system("pause");
return 0;
}