#if
#if
教程C 语言 的 #if
后面可以接常量表达式,如果常量表达式的值为真(非0),则对一段程序进行编译,否则对另一段程序进行编译。因此可使程序在不同条件下,完成不同的功能。
#if
详解#if expression
code1
#endif
如果表达式 expression 为真,那么就编译代码 code1,否则就不编译。
#if expression
code1
#else
code2
#endif
#if
也可以配合 #else
一起使用,这里说明,如果常量表达式 expression 为真,那么就编译代码 code1,否则就编译代码 code2。
#if
使用 #if
条件编译,执行编译代码
#include <stdio.h>
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
#define compile 1
#if compile
printf("Start compile\n");
#endif
return 0;
}
程序运行后,控制台输出如下图所示:
我们首先使用了 #if
来判断宏 compile 是否为真,如果为真,则执行 printf 对应的代码,因为,我们定义了 compile 为 1,所以 printf 代码被执行。现在,我们修改程序如下:
#include <stdio.h>
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
#define compile 0
#if compile
printf("Start compile\n");
#endif
return 0;
}
程序运行后,控制台输出如下图所示:
这次,我们使用了 #define
定义了 compile 宏为 0,此时,再次执行该程序,程序未执行 printf 代码。
#if
使用 #if
和 #else
执行不同的编译代码
#include <stdio.h>
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
#define compile 0
#if compile
printf("Start compile\n");
#else
printf("Do not compile\n");
#endif
return 0;
}
程序运行后,控制台输出如下图所示:
我们首先使用了 #if
来判断宏 compile 是否为真,如果为真,则执行第一个 printf 对应的代码,如果为假,那么就执行第二个 printf 代码。
因为,我们定义了 compile 宏为 0,所以执行了第二个 printf 代码。现在,我们修改程序如下:
#include <stdio.h>
int main()
{
printf("嗨客网(www.haicoder.net)\n\n");
#define compile 1
#if compile
printf("Start compile\n");
#else
printf("Do not compile\n");
#endif
return 0;
}
程序运行后,控制台输出如下图所示:
这次,我们看到,执行了第一个 printf 的代码。
#if
教程总结C 语言的 #if
后面可以接常量表达式,如果常量表达式的值为真(非0),则对一段程序进行编译,否则对另一段程序进行编译。因此可使程序在不同条件下,完成不同的功能。