Detect inappropriate variable usage within preprocessor #if

58 Views Asked by At

Consider the following arbitrary yet oversimplified code:

#define CONST_BAR 2

int foo(int x)
{
#if CONST_BAR > 0
    return x * CONST_BAR;
#else
    return x;
#endif
}

Suppose that we have many code blocks throughout multiple files that reference CONST_BAR in similar preprocessor directives. I'd like to refactor CONST_BAR to be a constexpr int instead. The problem is that if I fail to succeed in spotting all preprocessor directives that reference CONST_BAR in a similar manner, my code will suddenly be wrong in all places:

constexpr int CONST_BAR = 2;

int foo(int x)
{
#if CONST_BAR > 0
    return x * CONST_BAR;
#else
    return x;
#endif
}

The problem is that none of the compilers I'm using (MSVC, clang) emit an error or a warning that #if CONST_BAR > 0 is obviously incorrectly used, and the preprocessor directive will actually evaluate as false, changing the behavior of my function when that wasn't my intention. I really intended the following:

int foo(int x)
{
    if constexpr (CONST_BAR > 0)
    {
        return x * CONST_BAR;
    }
    return x;
}

How do I make a compiler spot this as an error so I can correct it?

0

There are 0 best solutions below