C++ – Preprocessor Directive vs if(constant) Statement: Which is Better?

c

Let's say we have a codebase that is used for many different costumers, and we have some code in it that is relevant only for costumers of type X. Is it better to use preprocessor directives to include this code only in costumer of type X, or to use if statements? To be clearer:

// some code
#if TYPE_X_COSTUMER  = 1
// do some things
#endif
// rest of the code

or

if(TYPE_X_COSTUMER) {
    // do some things
}

The arguments I can think about are:

  • Preprocessor directive results in smaller code footprint and less branches (on non-optimizing compilers)
  • If statements results with code that always compiles, e.g. if someone will make a mistake that will harm the irrelevant code for the project he works on, the error will still appear, and he will not corrupt the code base. Otherwise he will not be aware of the corruption.
  • I was always been told to prefer the usage of the processor over the usage of the preprocessor (If this is an argument at all…)

What is preferable – when talking about a code base for many different costumers?

Best Answer

I think there is one advantage of using a #define that you didn't mention, and that is the fact that you can set the value on the command line (thus, set it from your one-step build script).

Other than that, it is generally better to avoid macros. They don't respect any scoping and that can cause problems. Only very dumb compilers can't optimize a condition based on a compile-time constant. I don't know if that is a concern for your product (for example it might be important to keep the code small on embedded platforms).