Martin Pohorský Martin Pohorský - 4 months ago 31
C Question

Compiler: What if condition is always true / false

I think about conditionals and compilers. I am programming an application for Arduino and so I need the application to be as fast as possible.

In my code I have this:

#define DEBUG false


if (DEBUG)
String pinName;
pinName = "Pin ";
pinName += pin;
pinName += " initialized";

I am wondering if the compiler does not include the code (code in if block) in binary file. The conditions is always false, so the program never goes there.

And from the other side. What if DEBUG is true? Does Arduino test the condition or the compiler include only the body of if in binary file?

I found this site about #if directive, so I can rewrite the code to have these directives instead of "normal" if. But I would like to know if I should rewrite it or if it would be waste of time.


Any half-decent optimizing compiler will remove the whole code inside the if statement, if it can tell at compile-time that the condition always evaluates to false. Similarly, any half-decent compiler would skip the check itself if the condition is always true.

Indeed this is completely equivalent to "compiler switches" such as:

#define DEBUG

#ifdef DEBUG

The "compiler switch" syntax with #ifdef is to prefer, as it makes the intent clearer to other C programmers. But that's just a matter of coding style - it will result in the same binary as your original code.