#ifdef vs #if – which is better/safer as a method for enabling/disabling compilation of particular sections of code?

My initial reaction was #ifdef, of course, but I think #if actually has some significant advantages for this – here’s why:

First, you can use DEBUG_ENABLED in preprocessor and compiled tests. Example – Often, I want longer timeouts when debug is enabled, so using #if, I can write this

  DoSomethingSlowWithTimeout(DEBUG_ENABLED? 5000 : 1000);

… instead of …

#ifdef DEBUG_MODE
  DoSomethingSlowWithTimeout(5000);
#else
  DoSomethingSlowWithTimeout(1000);
#endif

Second, you’re in a better position if you want to migrate from a #define to a global constant. #defines are usually frowned on by most C++ programmers.

And, Third, you say you’ve a divide in your team. My guess is this means different members have already adopted different approaches, and you need to standardise. Ruling that #if is the preferred choice means that code using #ifdef will compile -and run- even when DEBUG_ENABLED is false. And it’s much easier to track down and remove debug output that is produced when it shouldn’t be than vice-versa.

Oh, and a minor readability point. You should be able to use true/false rather than 0/1 in your #define, and because the value is a single lexical token, it’s the one time you don’t need parentheses around it.

#define DEBUG_ENABLED true

instead of

#define DEBUG_ENABLED (1)

Leave a Comment