Reputation: 17768
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?
Upvotes: 2
Views: 1613
Reputation: 49986
You got good answers to check it in your compiler assembly output. I would like to share similar idiom that is very usefull to me sometimes:
int main(int argc, char ** argv)
{
const bool bDebug = false;
if(bDebug)
{
...
LOG(""); /// some heavy loging here
}
return 0;
}
so I leave such if-s in some relevant places in my code, and when I get a bug report that something bad happend I step through code and when I need to ouput some large arrays/data structures, I modify from debugger bDebug variable (actually I name them bVerbose), and then allow code to enter such IF-s. You dont have to recompile code to add heavy logging.
Upvotes: 1
Reputation: 71536
You cannot make the universal statement that every compiler will optimize the same things the same way. Likewise any compiler that might happen to do it today might not in some future version.
Yes, a number of compilers today can and will do that but that doesnt mean you should plan for it or expect it. If you dont want that code there, comment it out, ifdef it out or remove it.
As mentioned by others, try it and find out for yourself. If you are debugging something and suspect that this has or has not happened, simply look and find out...
Upvotes: 2
Reputation: 133587
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.
Upvotes: 3
Reputation: 12927
Yes, any decent C/C++ compiler will remove such if block.
Upvotes: 4
Reputation: 69687
You don't need to guess. Compile and step with debugger watching assembly instructions. You don't even need to be well familiar with assembly to see if there is actual code generated for lines in question or not.
Upvotes: 3