Search code examples
c++if-statementc-preprocessorcode-readability

Getting an if-statement to also check for a defined macro


I have an if-else where the if should check a flag and whether a macro is defined. I've come up with two solutions but am unsure on which of them to use.

  • Will there be a difference in execution time (or will compiler optimization eliminate this)?
  • Can the first solution cause bugs with the else when the flag isn't defined (i.e. due to lines written above or below the example code)?

Additionally:

  • Are there any commonly followed best practices that could apply to this situation?

1

#ifdef FLAG_A
    if(flagB)
    {
        ...
    }
    else
#endif
    {
        ...
    }

2

#ifdef FLAG_A
    bool flagA = true;
#else
    bool flagA = false;
#endif

    if(flagA && flagB)
    {
        ...
    }
    else
    {
        ...
    }

Solution

  • If the flagA variable is within a local scope (and remains unmodified within that scope), then the two will compile to be exactly the same (for most compilers, in non-debug build). If however flagA is a global, you'd need to declare it as 'constexpr' (which is probably a good idea in the other case!).

    Proof: https://godbolt.org/z/r9nra5

    In terms of best practices, I'm sure everyone will chip in with their own preference, but I prefer version 1. The only reason is that it's immediately clear that the code within the #ifdef / #endif block is conditionally compiled. It might not be immediately apparent when looking at case 2.