Home > Enterprise >  Compare two undefinded symbols in C
Compare two undefinded symbols in C

Time:10-05

I did not define both symboles SYMBOL1 and SYMBOL2, and I'm supprised when I see that the printf is called in the following code:

#include <stdio.h> 
int main()
{
#if (SYMBOL1==SYMBOL2)
    printf("Hello World");
#endif
    return 0;
}

Could you please explain why? any reference to the standard?

CodePudding user response:

As per the ISO C standard (C11 6.10.1 Conditional inclusion):

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. The resulting tokens compose the controlling constant expression which is evaluated ...

In other words, your expression becomes 0 == 0, which is obviously true. Hence the printf is included in the source stream.

CodePudding user response:

The compiler will not catch that your MACRO is undefined and it will consider it a 0. Since 0 == 0 printf will be executed.

The C standard says that all undefined identifiers there are replaced with 0.

CodePudding user response:

You should also check if both are defined, I think that if both (any) are undefined, you don't need to compile.

#if defined(SYMBOL1) && defined(SYMBOL1) && (SYMBOL1==SYMBOL2)
printf("Hello World");
#endif

(completely untested, but a rough idea).

edit: see also Preprocessor check if multiple defines are not defined

  • Related