Search code examples
cmacrospreprocessor

Undefined Macro in #if directive?


#include<stdio.h>
int main()
{
#if HELLO
   printf("%d\n",1);
#endif
}

In this code I am expecting error in the preprocessor stage because the maco HELLO is undefined. But it doesn't generate any error and simple ignore that printf statement. Why here #if directive act as #ifdef directive ?


Solution

  • C 2018 6.10.1 4 says that each identifier in a #if directive that is not either defined as a macro or used with the defined operator is replaced with 0:

    … After all replacements due to macro expansion and the defined unary operator have been performed, all remaining identifiers (including those lexically identical to keywords) are replaced with the pp-number 0, and then each preprocessing token is converted into a token.

    Regarding your statement:

    In this code I am expecting error in the preprocessor stage because the maco HELLO is undefined.

    You should not expect that because no statement in the C standard says that should happen, nor does any reputable third-party documentation say it should happen. As you learn to program, be on guard about making assumptions about how things should behave. Learn to rely on written documentation rather than intuition.