Sometimes I find that preprocessor directives aren’t flexible enough for my application, so I’ve been wondering if it is possible to exchange the #if functionality of the preprocessor.
Example:
const bool Debug = false;
if (Debug)
{
...
}
Will the if statement and its content be removed by the compiler? Alternatively, if a the Debug constant’s value is true, will the compiler remove the condition check and keep the contents in place?
Yes, and yes. However, those are implementation details, not guarantees of the language.
Some interesting aspects of using
if(false)to control conditional compilation:The compilation is not conditional at all; the body of the
ifwill be compiled just like any other code. If it contains syntax errors, you’ll get syntax errors. If it contains overload resolution errors, you’ll get overload resolution errors. “Go to usage” and other IDE features continue to work.This is very different from controlling with
#if false; text that is omitted because of the preprocessor is treated as comments. “Go to usage” will not find a usage that is conditionally compiled out, you don’t get syntax colouring, and so on. However, the code can be completely broken because, after all, it is basically just a comment.However, the first point is a slight lie; there is one difference. Code inside
if(false)is not checked for definite assignment errors:Because after all, there is no way that x is going to be read before it is written in this program fragment!