c++optimization

Will A Compiler Remove An If Block That Always Evaluates to Zero?


Will the compiler remove this if statement?

 #define DEBUG 0
 int main(int argc, char ** argv)
 {
    if(DEBUG)
    {
       ...
    }
    return 0;
 }

I tried to google this, and search stackoverflow but I think my search terms were bad because I couldn't find the information.

If this is optimized what would I want to read about to learn about the optimization?


Solution

  • I'm not sure if a compiler can optimize it away. I guess yes since in this situation you couldn't have any side effect, so it can be safely removed without changing semantics of the code.

    In any case guessing is not nice and relying on an optimization is not nice too.

    Why don't you use a #ifdef .. #endif block instead that a code block?

    #define DEBUG
    
    #ifdef DEBUG
      ...
    #endif
    

    In this way you will have a sure outcome.