Do short-circuit operators run from left to right?

So, if the code is:

if(f() && false) { // never happens } 

Is it possible to always be sure that f() will be called and not "optimized" by the compiler?

+4
source share
1 answer

The javac compiler does very little optimization.

JIT can optimize the code, but in this case you can be sure that && and || always ranked from left to right.

All binary operators, with the exception of assignment operators, are evaluated from left to right

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html


From JLS.

15.7. Assessment Procedure

The Java programming language ensures that operands of operators will be evaluated in a specific evaluation order, namely, from left to right.

It is recommended that code not rely on this specification. The code is usually clearer when each expression contains no more than one side effect, like its most external operation, and when the code does not depend on what kind of exception arises from evaluating the expressions from left to right.

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html

+7
source

Source: https://habr.com/ru/post/1433312/


All Articles