## #ifdef的形式
预处理程序提供了条件编译的功能。条件编译有三种形式,下面分别介绍。
第一种形式
第一种形式的格式为:
```#ifdef 标识符
程序段1
#else
程序段2
#endif```
功能是,如果标识符已被 #define命令定义过则对程序段1进行编译;否则对程序段2进行编译。如果没有程序段2(它为空),本格式中的#else可以没有,即可以写为:
```#ifdef 标识符
程序段
#endif```#include "stdio.h"
#define NUM ok
int main(void){
struct stu{
int num;
char *name;
char sex;
float score;
} *ps;
ps=(struct stu*)malloc(sizeof(struct stu));
ps->num=102;
ps->name="Zhang ping";
ps->sex='M';
ps->score=62.5;
#ifdef NUM
printf("Number=%d\nScore=%f\n",ps->num,ps->score);
#else
printf("Name=%s\nSex=%c\n",ps->name,ps->sex);
#endif
free(ps);
return 0;
}
由于在程序的第15行插入了条件编译预处理命令,因此要根据NUM是否被定义过来决定编译那一个printf语句。而在程序的第一行已对NUM作过宏定义,因此应对第一个printf语句作编译故运行结果是输出了学号和成绩。
第二种形式
第二种形式的格式为:
```#ifndef 标识符
程序段1
#else
程序段2
#endif```
与第一种形式的区别是将“ifdef”改为“ifndef”。它的功能是,如果标识符未被#define命令定义过则对程序段1进行编译,否则对程序段2进行编译。这与第一种形式的功能正相反。
第三种形式
第三种形式的格式为:
```#if 常量表达式
程序段1
#else
程序段2
#endif```
它的功能是,如常量表达式的值为真(非0),则对程序段1 进行编译,否则对程序段2进行编译。因此可以使程序在不同条件下,完成不同的功能。
#include "stdio.h"
#define R 1
int main(void){
float c,r,s;
printf ("input a number: ");
scanf("%f",&c);
#if R
r=3.14159*c*c;
printf("area of round is: %f\n",r);
#else
s=c*c;
printf("area of square is: %f\n",s);
#endif
return 0;
}
本例中采用了第三种形式的条件编译。在程序第1行宏定义中,定义R为1,因此在条件编译时,常量表达式的值为真,故计算并输出圆面积。