2

Do modern compilers optimize a piece of code like if(CONSTANT) { ... }, where CONSTANT is a literal, template argument, const variable or constexpr variable? Do they remove the whole if(0) { ... } expression or "throw out" the if(1) part in if(1) { ... }?

9
  • 4
    Check the assembly output with the if(constant) and check the output without it. As far as I know a lot of compilers will make this type of optimization with the optimization level set high enough, if CONSTANT is truly a constant.
    – shuttle87
    Jun 29, 2014 at 20:32
  • 2
    Being a const variable doesn't necessarily mean the compiler knows the value.
    – chris
    Jun 29, 2014 at 20:33
  • 1
    @quetzalcoatl Thanks. The accepted answer is helpful. But note that the only "question part" in that question is "how does the compiler optimize a method that is declared const vs one that isn't". I can't see how my question duplicates that one.
    – cubuspl42
    Jun 29, 2014 at 20:43
  • 2
    Simple live demo
    – Kerrek SB
    Jun 29, 2014 at 20:47
  • 1
    cubuspl42 - I agree that's not the best 'duplicate' reference, but still far more useful than this more-of-a-duplicate. Strangely, I coulnd't find any better ones (still, I know they exist, this question is quite common), so I linked the one that gives most useful information. Jun 29, 2014 at 20:54

1 Answer 1

2

This is not guaranteed but most compilers of good quality will do it.

C99 Rationale says in 6.4.9:

if (0) {
 /* code to be excluded */
}

Many modern compilers will generate no code for this if statement.

For example with gcc (in C) an assembly dump shows that dead code with either if (0) .. else or if (1) .. else is optimized out even in -O0.

2
  • @quetzalcoatl I finally removed the #if 0 part of the quote to not confuse the reader.
    – ouah
    Jun 29, 2014 at 20:54
  • Sorry, I didnt meant to push work on you, I just left a note for random readers. But many thanks! now that's much clearer and informative! Jun 29, 2014 at 20:55

Not the answer you're looking for? Browse other questions tagged or ask your own question.