条件编译

来源:互联网 发布:鬼宿舍知乎 编辑:程序博客网 时间:2024/05/16 06:33
/*第一种形式的格式为:    #ifdef  标识符        程序段1    #else        程序段2    #endif它的功能是,如果标识符已被 #define命令定义过则对程序段1进行编译;否则对程序段2进行编译。如果没有程序段2(它为空),本格式中的#else可以没有,即可以写为:    #ifdef  标识符        程序段    #endif*/ #include <stdio.h>#define NUM okint 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//条件判断,是否有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;}

第二种形式

第二种形式的格式为:
#ifndef 标识符
程序段1
#else
程序段2
#endif
与第一种形式的区别是将“ifdef”改为“ifndef”。它的功能是,如果标识符未被#define命令定义过则对程序段1进行编译,否则对程序段2进行编译。这与第一种形式的功能正相反。

第三种形式

第三种形式的格式为:
#if 常量表达式
程序段1
#else
程序段2
#endif
它的功能是,如常量表达式的值为真(非0),则对程序段1 进行编译,否则对程序段2进行编译。因此可以使程序在不同条件下,完成不同的功能。

#include <stdio.h>#define R 1int 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或程序段2,生成的目标程序较短。如果条件选择的程序段很长,采用条件编译的方法是十分必要的。

0 0
原创粉丝点击