C语言教程-C中的#ifdef

#ifdef预处理指令用于检查宏是否由#define定义。如果是,则执行代码,否则执行#else代码(如果存在)。
语法:
#ifdef 宏名
//代码
#endif
带有#else的语法:
#ifdef 宏名
//成功的代码
#else
//否则的代码
#endif
C #ifdef示例
让我们看一个简单的例子来使用#ifdef预处理指令。
#include <stdio.h>
#include <conio.h>
#define NOINPUT
void main() {
int a = 0;
#ifdef NOINPUT
a = 2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
输出:
Value of a: 2
但是,如果您不定义NOINPUT,它将要求用户输入一个数字。
#include <stdio.h>
#include <conio.h>
void main() {
int a = 0;
#ifdef NOINPUT
a = 2;
#else
printf("Enter a:");
scanf("%d", &a);
#endif
printf("Value of a: %d\n", a);
getch();
}
输出:
Enter a: 5
Value of a: 5