Jump to content

User talk:ThirtySixDegrees

Page contents not supported in other languages.
From Wikipedia, the free encyclopedia

Hello,

You asked a question on my talk page about dead code elimination, and the difference between "if(0) {}" and "#if 0".

As a programmer, if you're just trying to remove some block of code, and you have optimizations turned on in the compiler, then there's no real difference between "if(0)", "#if 0", and commenting out the lines. The compiler will produce the same output code in both cases.

(Actually, that's not true. If you put "#if 0" around a bunch of plain text or garbage, then it will be removed and the compiler won't notice it. But if you write "if(0)", then the stuff inside needs to still be valid code, even if it will be removed later. But that has nothing to do with dead code elimination.)

However, there are reasons why it might be better to use "if(0)". Specifically, that's an actual piece of code, rather than a preprocessor directive. If you use "#if 0", then it's removed from the input by the preprocessor before the compiler even sees it. The compiler doesn't have a chance to make any decisions about the code, because as far as it's concerned it doesn't exist.

So if you're just writing "if(0)", then it probably doesn't make much difference, but that's not the only way dead code elimination can come in to play. For instance, if you write "if(x==1)" but the compiler knows that x is always 3, it will simplify "x==1" to just "0", and then it becomes dead code. Other comparisons can simplify like that, such as testing if an unsigned number is <0.

The opposite applies, too. If you write "if(1)", the compiler will keep the block inside the "if", but the test itself will disappear. And tests that always return true will be similarly simplified.

As for why, as a programmer, you'd want to do that... it's the difference between compile-time and run-time. If you use #ifs to do everything, you can only set those options at compile-time. If, however, you write "if(thing_enabled)" then you could either make thing_enabled a const, and get the same optimization as the compile-time version, or you could make it a variable that can be changed at run-time. It just depends on what you're trying to do.

Hope that answers your question. Bigpeteb (talk) 16:56, 16 August 2012 (UTC)[reply]