Reputation: 618
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.
else
when the flag isn't defined (i.e. due to lines written above or below the example code)?Additionally:
1
#ifdef FLAG_A
if(flagB)
{
...
}
else
#endif
{
...
}
2
#ifdef FLAG_A
bool flagA = true;
#else
bool flagA = false;
#endif
if(flagA && flagB)
{
...
}
else
{
...
}
Upvotes: 0
Views: 174
Reputation: 9682
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.
Upvotes: 1