C/C++ gotcha – using #if true

Posted: 14th April 2014 by Tim in C, C++
Tags: , , , , , , ,

Consider the following code, which compiles without warnings with both gcc and g++:

#include <stdio.h>

int main(int argc, char **argv)
{
#if true
    printf("This does what you expect\n");
#else
    printf("This does not do what you expect!\n");
#endif

    return 0;
}

When compiling with g++, the program prints This does what you expect. However, when compiling with gcc, This does not do what you expect!

The problem here is with the #if true statement. In C++, true is a keyword which (unsurprisingly) evaluates to true. However, in C there is no such keyword, so true is just an undefined macro. #if <undefined_macro> will always evaluate to false, hence why the #else block is evaluated instead.

If you’re writing code which is used in both C and C++, use #if 0 or #if 1 instead as this is guaranteed to behave in the same way in both languages.