如何获得#if预处理器条件包含一个变量而不产生错误?

pra*_* pp 2 c c-preprocessor

#if包含编译时变量的预处理程序阶段语句如何在预处理器阶段自行解析?

下面是运行没有任何错误的代码:

#include<stdio.h> 

void main()
{
   int num=10; /* compile time */

#if((num%2)==0)  /* #if is preprocessor stage but has num of compile time why not error here? */
   printf("\nNumber is Even");
#else
   printf("\nNumber is Odd");
#endif 
}
Run Code Online (Sandbox Code Playgroud)

Jen*_*edt 11

对于评估#if,预处理器通过适当的扩展替换已定义宏的所有标识符.之后保留的所有标识符都具有该值0.

  • `num`不是定义的预处理器符号,因此它获得值"0".`0%2`为'0`,因此选择了第一个'printf`._compiler_符号`num`的存在无效. (3认同)