与使用条件编译有点混淆

  • 本文关键字:编译 条件 c
  • 更新时间 :
  • 英文 :


在学习条件编译的概念时,我遇到了一些问题。我试图定义一个符号常量,如果值不是我所期望的,就改变它的值。并且面临一些错误

这是代码

// Demonstrating conditional compilation
#include <stdio.h>
#define PI 3.14
int main()
{
#if (PI==3.14)
printf("Correct value!");
#else
#undef PI
#define PI 3.14
printf("Correct value assigned!");
#endif
}

这就是错误

Starting build...
/usr/bin/gcc -fdiagnostics-color=always -g "/home/karthik/karthik/Learning-C-Lang/Learning_C/10. Preprocessor/Preprocessor DIrectives/programs/programs/conditional_compilation_demo.c" -o "/home/karthik/karthik/Learning-C-Lang/Learning_C/Misc/Binaries (compiled on Linux)/Binaries/conditional_compilation_demo"
/home/karthik/karthik/Learning-C-Lang/Learning_C/10. Preprocessor/Preprocessor DIrectives/programs/programs/conditional_compilation_demo.c: In function ‘main’:
/home/karthik/karthik/Learning-C-Lang/Learning_C/10. Preprocessor/Preprocessor DIrectives/programs/programs/conditional_compilation_demo.c:4:12: error: floating constant in preprocessor expression
4 | #define PI 3.14
|            ^~~~
/home/karthik/karthik/Learning-C-Lang/Learning_C/10. Preprocessor/Preprocessor DIrectives/programs/programs/conditional_compilation_demo.c:8:10: note: in expansion of macro ‘PI’
8 |     #if (PI==3.14)
|          ^~
/home/karthik/karthik/Learning-C-Lang/Learning_C/10. Preprocessor/Preprocessor DIrectives/programs/programs/conditional_compilation_demo.c:8:14: error: floating constant in preprocessor expression
8 |     #if (PI==3.14)
|              ^~~~
Build finished with error(s).

但是这个代码可以

// Write a program to calculate the area of a circle. Make a symbolic constant for PI.
#include <stdio.h>
// Define a symbolic constant PI
// It is a convention to name symbolic constants in uppercase
#define PI 3.14 
int main()
{
int r;
printf("Enter radius: ");
scanf("%d",&r);
printf("Area = %f", PI*r*r);
}

如本线程所述:

您可以使用C预处理器进行整数运算;你不能用它做浮点运算。

显然,C预处理器不允许在条件运算符中使用浮动常量。

最新更新