Search code examples
c++debugging

C++: contst static DEBUG and if statements, what is the actual execution-time overhead?


At school I was often taught that preprocessor statements can easily go haywire, since the strings you define, eg:

#define PI 3.1415926

are substituted every where in your code, leading to weird substitutions when a variable name contains the string PI.

Therefore, when debugging, I steer away from the following approach:

#define _DEBUG
...
#ifdef _DEBUG
    // debug code
#endif
...

but tought it would be "safer" to use:

const static bool DEBUG = true
int main()
{
    ...
    if(DEBUG){ /* debug code*/ }
    ...
}

This works well but I was wondering what, in comparison to the preprocessor statement approach, the overhead is at run-time for this approach? With the preprocessor approach everything happens before compilation,so no run-time overhead is to be expected.

I know that the overhead for a simple if-statement is pretty much neglectabe, yet this doesn't hold when it is put deep in to some nested loops that run for a large number of times (small things add up to big things).

Does the compiler recognize the fact that DEBUG is const static and hard-code this into the executable, already enabling or disabling the debug code at compile-time? What makes me suspect this is that the other day, when working in some unrelated code, the compiler warned me about some part of the code being obsolete because the if-statement surrounding it would never become true (if I remember correctly).


Solution

  • It's impossible to give a hard guarantee: it is up to each individual compiler what it does with the code you feed it.

    However, any real-world compiler will optimize this out for you. It is one of the simplest, most trivial optimizations that exist, and most compilers would probably do it even if you disable optimizations.

    It just doesn't make sense to generate code for what's essentially if (true).

    So there should be zero overhead at runtime.