#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. #define
s 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)
They're both hideous. Instead, do this:
#ifdef DEBUG
#define D(x) do { x } while(0)
#else
#define D(x) do { } while(0)
#endif
Then whenever you need debug code, put it inside D();
. And your program isn't polluted with hideous mazes of #ifdef
.
#ifdef
just checks if a token is defined, given
#define FOO 0
then
#ifdef FOO // is true
#if FOO // is false, because it evaluates to "#if 0"