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) { ... }?

cubuspl42
  • 7,833
  • 4
  • 41
  • 65
  • 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 '14 at 20:32
  • 2
    Being a `const` variable doesn't necessarily mean the compiler knows the value. – chris Jun 29 '14 at 20:33
  • It depends on the compiler and all flags. Usually it will be removed, if optimization is on and the "debugging support" is off. Of course assuming it is a real compile-time constant. – quetzalcoatl Jun 29 '14 at 20:33
  • @shuttle87 That's an idea, but note that not all C/C++ programmers (especially beginners) can read assembly. – cubuspl42 Jun 29 '14 at 20:34
  • Modern compilers do all optimizations their authors found time to teach them, which preserve the semantics of correct programs, where those same authors didn't think them too dangerous. – Deduplicator Jun 29 '14 at 20:34
  • 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 '14 at 20:43
  • 2
    [Simple live demo](http://ideone.com/KzvJfQ) – Kerrek SB Jun 29 '14 at 20:47
  • @KerrekSB That's an interesting trick. – cubuspl42 Jun 29 '14 at 20:48
  • 1
    cubuspl42 - I agree that's not the best 'duplicate' reference, but still far more useful than this [more-of-a-duplicate](http://stackoverflow.com/questions/13995659/can-modern-compilers-optimize-constant-expressions-where-the-expression-is-deriv). 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. – quetzalcoatl Jun 29 '14 at 20:54

1 Answers1

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.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • @quetzalcoatl I finally removed the `#if 0` part of the quote to not confuse the reader. – ouah Jun 29 '14 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! – quetzalcoatl Jun 29 '14 at 20:55