Bitwise AND (&) expression in Java

后端 未结 2 1181
自闭症患者
自闭症患者 2021-01-24 19:17

I am debugging code that has in it expr1 & expr2 where expr1 has a side effect that affects expr2 evaluation result. I suspect that

2条回答
  •  野的像风
    2021-01-24 19:34

    The evaluation order is well-defined in the specification:

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

    The HotSpot optimizer should not make an optimization that results in expr2 being evaluated before expr1 if this changes the result. If it does this it is a bug.

    Note also it says:

    It is recommended that code not rely crucially on this specification.

    Your code could be rewritten more clearly as follows:

    int a = expr1;
    int b = expr2;
    int result = a & b;
    

提交回复
热议问题