Java Reference
In-Depth Information
5.3.2 Short-Circuited
&&
Consider the logical
&&
operator. In a logical expression like
arg
1
&&
arg
2
The semantics of Java, and so of j--, require that the evaluation of such an expression be
short-circuited. That is, if arg
1
is
false
, arg
2
is not evaluated;
false
is returned. If arg
1
is
true
, the value of the entire expression depends on arg
2
. This can be expressed using
the Java conditional expression, as arg
1
?
arg
2
:false
. How do we generate code for this
operator? The code to be generated depends of whether the branch for the entire expression
is to be made on
true
, or on
false
:
Branchtotargetwhen Branchtotargetwhen
arg1&&arg2istrue:
arg1&&arg2isfalse:
branchtoskipif branchtotargetif
arg1isfalse arg1isfalse
branchtotargetwhen branchtotargetif
arg2istrue
arg2isfalse
skip:...
For example, the code generated for
if(a>b&&b>c){
c=a;
}
else{
c=b;
}
would be
0:iload_1
1:iload_2
2:if_icmple15
5:iload_2
6:iload_3
7:if_icmple15
10:iload_1
11:istore_3
12:goto17
15:iload_2
16:istore_3
17:...
The
codegen()
method in
JLogicalAndOp
generates the code for the
&&
operator:
publicvoidcodegen(CLEmitteroutput,StringtargetLabel,
booleanonTrue){
if(onTrue){
StringfalseLabel=output.createLabel();
lhs.codegen(output,falseLabel,false);
rhs.codegen(output,targetLabel,true);
output.addLabel(falseLabel);
}else{
lhs.codegen(output,targetLabel,false);
rhs.codegen(output,targetLabel,false);
}
}
Search WWH ::
Custom Search