Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will the Compiler Optimize this out

Say I have something like this in a C Code. I know you can use a #define instead, to make the compiler not compile it, but just out of curiosity I'm asking if the compiler will also figure this thing out.

I think this is even more important for Java Compiler as it does not support #define.

const int CONDITION = 0;
........
// Will the compiler compile this?
if ( CONDITION )
{

}
.......
like image 837
MetallicPriest Avatar asked Aug 19 '11 14:08

MetallicPriest


People also ask

How does a compiler optimize?

Compiler optimization is generally implemented using a sequence of optimizing transformations, algorithms which take a program and transform it to produce a semantically equivalent output program that uses fewer resources or executes faster.

Do compilers Optimise code?

Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed.

Do compilers optimize loops?

Compilers do this optimization every time they can, under the condition they can establish that the expression is loop invariant. In the case of variable operation , the situation is a bit more complex. The variable is loop invariant, but it determines the control flow inside the loop.

Does the Java compiler optimize?

The JVMs JIT compiler is one of the fascinating mechanisms on the Java platform. It optimizes your code for performance, without giving away its readability. Not only that, beyond the “static” optimization methods of inlining, it also makes decisions based on the way that the code performs in practice.


1 Answers

in Java, the code inside the if won't even be part of the compiled code. It must compile, but it won't be written to the compiled bytecode. It actually depends on the compiler, but I don't know of a compiler that doesn't optimize it. the rules are defined in the JLS:

An optimizing compiler may realize that the statement x=3; will never be executed and may choose to omit the code for that statement from the generated class file, but the statement x=3; is not regarded as "unreachable" in the technical sense specified here.

The rationale for this differing treatment is to allow programmers to define "flag variables" such as:

static final boolean DEBUG = false;

and then write code such as:

if (DEBUG) { x=3; }

The idea is that it should be possible to change the value of DEBUG from false to true or from true to false and then compile the code correctly with no other changes to the program text.

Don't know about C.

like image 98
JB Nizet Avatar answered Oct 05 '22 12:10

JB Nizet