Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

&& does not short-circuit correctly in #if

For code:

#if defined(FOO) && FOO(foo)
    #error "FOO is defined."
#else
    #error "FOO is not defined."
#endif

MSVC 19.38 prints:

<source>(1): warning C4067: unexpected tokens following preprocessor directive - expected a newline
<source>(4): fatal error C1189: #error:  "FOO is not defined."

ICX 2024.0.0 and Clang 18.1 prints:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<source>:1:21: error: function-like macro 'FOO' is not defined
    1 | #if defined(FOO) && FOO(foo)
      |                     ^
<source>:4:6: error: "FOO is not defined."
    4 |     #error "FOO is not defined."
      |      ^
2 errors generated.

GCC 14.1 prints:

<source>:1:24: error: missing binary operator before token "("
    1 | #if defined(FOO) && FOO(foo)
      |                        ^
<source>:4:6: error: #error "FOO is not defined."
    4 |     #error "FOO is not defined."
      |      ^~~~~
Compiler returned: 1

Why does every compiler but MSVC print an error about an undefined macro when FOO is not undefined (although MSVC prints a warning too)? Is there some special semantic that I am not seeing here?

FOO(foo) should not be evaluated if defined(FOO) evaluates to false.

>Solution :

If FOO is not defined (or is defined but not as a function-like macro), then FOO(foo) is a syntax error.

The #if directive expects an integer constant expression to follow it (including expressions of the form "defined identifier"). Since FOO(foo) can’t be expanded due to FOO not being defined, this is not an integer constant expression.

You would get a similar error for something like this:

int main()
{
    int x = some_valid_expression && undeclared_identifier;
    return 0;
}

To do what you want, you need to break up the #if directive into multiple ones:

#if defined(FOO)
    #if FOO(foo)
        #error "FOO is defined and non-zero."
    #else
        #error "FOO is zero."
    #endif
#else
    #error "FOO is not defined."
#endif
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading