请分析以下一组宏所定义的输出格式:
#define NL putchar('\n')
#define PR(format,value) printf("value=%format\t",(value))
#define PRINT1(f,x1) PR(f,x1);NL
#define PRINT2(f,x1,x2) PR(f,x1)
RINT1(f,x2)
如果在程序中有以下的宏引用:
PR(d,x);
PRINT1(d,x);
PRINT2(d,xl,x2);
写出宏展开后的情况,并写出应输出的结果,设x=5、x1=3、x2=8。
解:展开后为:
printf("value=%format\t",(x));
printf("value=%format\t",(x));putchar('\n');
printf("value=%format\t",(x1));printf("value=%format\t",(x2));putchar('\n');
如果运行以下程序:(xt9-5.c)
#include <stdio.h>
#define NL putchar('\n')
#define PR(format,value) printf("value=%format\t",(value))
#define PRINT1(f,x1) PR(f,x1);NL
#define PRINT2(f,xl,x2) PR(f,x1)
RINT1(f,x2)
void main()
{ float x=5.0,x1=3.0,x2=8.0;
char d;
PR(d,x);
PRINT1(d,x);
PRINT2(d,xl,x2);
}
输出结果如下:
value=5.000000otmat value=5.000000ormat
value=3.000000ormat value=8.000000ormat
通过本习题可以看到:如果用Turbo C,则不能用这种方法将输出格式和输出项都作为参数。在宏替换时对字符串中的字符不予替换,一律保留原状。