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 )
{
}
.......
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.
Compilers are free to optimize code so long as they can guarantee the semantics of the code are not changed.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With