compilation error on boolean expression

前端 未结 4 569
春和景丽
春和景丽 2021-01-25 23:56

This is a snippet of Java code:

static boolean a; // gets false
static boolean b; 
static boolean c;

    public void printA(){

         boolean bool = (a = tru         


        
4条回答
  •  梦毁少年i
    2021-01-26 00:22

    If I might....

    It looks like some people aren't quite getting what the question is.

    x = (a=true) || (b=true) && (c==true);

    Since && has a higher precedence than ||, it seems like (b=true) && (c==true) should be evaulated first, thus setting b and c to true. If && has higher precedence, why is one of the operands for the || evaluated first?

    And Rohit Jain has explained it the best so far. All I might add is that precedence of operators doesn't dictate the order in which the operands are evaluated -- merely what operations must be completed as operands for for other operators if not rendered unnecessary by short-circuit operators. The precedence determines the tree for the expression (with, ironically, higher-precedent operators going lower in the tree), but then the tree is evaluated depth-first and left-to-right, regardless of operators precedence.

         ||
       /    \
     =      &&
    / \    /   \
    a t    =   =
          / \ / \
          b t c t
    

    First the a=true is evaluated, with the "side effect" of doing the assignment, to a value of true. Since || short circuits, the other side isn't even looked at.

    If you really want the && (and its operands) to be evaluated first, you'd have to rewrite the expression:

    x = (b=true) && (c=true) || (a=true);

    Of course, then b and c are set to true and a remains false because || short circuits.

    I don't think I've explained anything new, just the same info in smaller steps.

提交回复
热议问题