【例15.2】定义正确,使用不正确的例子。
#include <stdio.h> #define INT_PTR int* void main () { INT_PTR a ,b ; int c=25 ; a=&c ; c=5* *a*5 ; b=a ; printf ("%d ,%d\n" ,*a ,*b ); }
宏定义INT_PTR为整数指针int*,但在程序中,语句
INT_PTR a ,b ;
在展开后,变为
int *a , b ;
变量a是指针类型,但变量b却是整数类型。也就是说,每次只能声明一个变量。即
INT_PTR a ;INT_PTR b ;
或者采用如下等效声明:
INT_PTR a ,*b ;
另外,为了提高易读性,c的表达式最好将指针*a括起来。最终程序如下。
#include <stdio.h> #define INT_PTR int* void main () { INT_PTR a , *b ; int c=25 ; a=&c ; c=5* (*a )*5 ; b= (int* )*a ; printf ("%d ,%d\n" ,*a ,b ); }
a是指针且指向整数变量a的地址,*a就是变量c的整数值。使用强制转换将这个值转换为指针类型并赋给指针b,所以运行结果为625,625。
【例15.3】下面的程序不能通过编译,请找出问题并改正之。
#include <stdio.h> #include <math.h> #define ABORT (msg ) printf ("%s\n" ,msg ); void root (const double a ) { if (a<0 ) ABORT (" 数值小于0 ,不能开平方"" ); else printf ("%f\n" ,sqrt (a )); } void main () { double a=30.25 ,b=-9 ; root (a ); root (b ); }
编译出错,信息为:
error C2181 : illegal else without matching if
宏定义很简单,也没发现错误。仔细检查if语句,看起来好像并没有写错。现在把它展开,语句变为
if (a<0 ) printf ("%s\n" ,msg );; else printf ("%f\n" ,sqrt (a ));
原来else之前多了一个“;”号。如果不改变宏定义,可以使用“{}”号使if后面的语句变为复合语句以便去除这个多余的“;”号,即
if (a<0 ) {printf ("%s\n" ,msg );;} else printf ("%f\n" ,sqrt (a ));
也就是root函数的定义改为:
void root (const double a ) { if (a<0 ) {ABORT (" 数值小于0 ,不能开平方!" );} else printf ("%f\n" ,sqrt (a )); }
当然,也可以将宏定义改变为:
#define ABORT (msg ) printf ("%s\n" ,msg )
后一种方式可能更贴切一些。输出结果如下:
5.500000 数值小于0 ,不能开平方!