Java表达式中子表达式的求值顺序 [英] order of evaluation of subexpressions in a Java expression

查看:107
本文介绍了Java表达式中子表达式的求值顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码段:

int x=2,y=3;
if ( (y == x++) | (x < ++y) )
// rest of code

我知道在C ++中,您被教导不要依赖于子表达式的求值顺序,因为根本不能保证它是任何顺序. 因此,此代码将是错误的,并且不能保证条件下表达式所产生的布尔值是真实的(例如,可以在第一次等式测试中对y进行递增运算). 由于我是在Java认证书中阅读此代码的,因此我假设Java并非如此..我的意思是,我是否保证Java的评估顺序始终是从左到右?因此,上面的表达式应始终为true.

I know that in C++ you're taught not to rely on evaluation order of subexpression,because it's not guaranteed to be any order at all. So this code would be in error,and the boolean yielded by the expression in the condition is not guaranteed to be true ( y could be incremented before it is evaluated in the first equality test,for example ). Since I read this code in a Java certification book,I assume that this isn't the case with Java..I mean, am I guaranteed that order of evaluation in Java is always left to right? So the above expression should always yield true.

推荐答案

是的,可以保证从左到右执行-至少可以像实际那样执行.这是在 JLS 15.7 :

Yes, it's guaranteed to be executed from left to right - or at least, act as if it is. This is defined in JLS 15.7:

Java编程语言保证运算符的操作数似乎按照特定的评估顺序(即从左到右)进行评估.

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

|运算符的第一个操作数将得出3 == 2,并得出false,但是第二个操作数将得出3<. 4,并得出true.

The first operand of the | operator will evaluate 3 == 2, and yield false, but the second operand will evaluate 3 < 4, and yield true.

话虽如此,我绝对会避免需要非常仔细阅读的代码...

Having said that, I would definitely avoid code that requires that much careful reading...

这篇关于Java表达式中子表达式的求值顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆