Why no warning with "#if X" when X undefined?

Viewed 10631

I occasionally write code something like this:

// file1.cpp
#define DO_THIS 1

#if DO_THIS
    // stuff
#endif

During the code development I may switch the definition of DO_THIS between 0 and 1.

Recently I had to rearrange my source code and copy some code from one file to another. But I found that I had made a mistake and the two parts had become separated like so:

// file1.cpp
#define DO_THIS 1

and

// file2.cpp
#if DO_THIS
    // stuff
#endif

Obviously I fixed the error, but then thought to myself, why didn't the compiler warn me? I have the warning level set to 4. Why isn't #if X suspicious when X is not defined?

One more question: is there any systematic way I could find out if I've made the same mistake elsewhere? The project is huge.

EDIT: I can understand having no warning with #ifdef that makes perfect sense. But surely #if is different.

8 Answers

If DO_THIS is yours definition then simple and working solution seems to be usage of Function-like Macro:

#define DO_THIS() 1

#if DO_THIS()
    //stuff
#endif

I tested this under Visual Studio 2008, 2015 and GCC v7.1.1. If DO_THIS() is undefined VS gererates:

warning C4067: unexpected tokens following preprocessor directive - expected a newline

and GCC generates

error: missing binary operator before token "("

Related