5. 6. 在定义宏时,可以引用已定义的宏名,层层置换。例:#include#define R 3.0#define PI 3.14159#define L 2*PI*R#define S PI*R*Rvoid main(){printf(“L=%f\nS=%f\n”, L, S);}7. 对程序中用双引号引起的显式字符串即便和宏名相同也不进行置换。8. 宏定义与变量定义不同,只做字符串替换,不占内存单元。返回
6. 宏定义例题#include#define PI 3.1415926#define S(r) PI*r*rvoid main(){ float a, area; a=3.6; area=S(a); printf(“r=%f\narea=%f\n”, a, area);}area=S(a);展开得结果是area=3.1415926*a*a;S(r)=PI*r*r
Area=S(a)
=PI*a*a
=3.1415926*3.6*3.6
11. 如果善于利用宏,可以使程序简单化。
#define PR printf #define NL "\n" #define D "%d\t" #define D1 D NL #define D2 D D NL #define D3 D D D NL #define D4 D D D D NL #define S "%s" #include void main()
{int a, b, c,d;
char string[]="CHINA";
a=1; b=2; c=3; d=4;
PR(D1, a);
PR(D2, a, b);
PR(D3, a, b, c);
PR(D4, a, b, c, d);
PR(S, string);
}1
12
123
1234
CHINA返回
13. 注意:包含处理是在编译时完成的,当被包含的文件修改后,所有包含它的文件必须全部重新编译。
#define PR printf
#define NL "\n"
#define D "%d\t"
#define D1 D NL
#define D2 D D NL
#define D3 D D D NL
#define D4 D D D D NL
#define S "%s"
#include #include “format.h”
void main()
{int a, b, c,d;
char string[]="CHINA";
a=1; b=2; c=3; d=4;
PR(D1, a);
PR(D2, a, b);
PR(D3, a, b, c);
PR(D4, a, b, c, d);
PR(S, string);
}format.h文件:file1.c文件:
19. #include
#define LETTER 1
void main()
{char str[20]="C Language", c;
int i;
i=0;while ((c=str[i])!='\0')
{i++;
#if LETTER
if (c>='a'&&c<='z')
c=c-32;
#else
if (c>='A'&&c<='Z')
c=c+32;
#endif
printf("%c", c);
}
}#define LETTER 1
结果为:C LANGUAGE
#define LETTER 0
结果为:c language返回