Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
172 views
in Technique[技术] by (71.8m points)

java - 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 )
{

}
.......
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.9k users

...