Why does the “or” go before the “and”?

前端 未结 3 1596
星月不相逢
星月不相逢 2020-12-11 20:18
int it=9, at=9;

if(it>4 || ++at>10 && it>0)  
{
    System.out.print(\"stuff\");    
}

System.out.print(at);

prints out stuff9 a

3条回答
  •  暖寄归人
    2020-12-11 20:57

    I feel I should add how to actually get your expected output.

    Brief explanation: the || operator short-circuits the entire expression, thus the right side not even being evaluated.

    But, to not short-circuit and get your expected output, instead of the || operator, just use |, like so:

    int a = 9, b = 9;
    
    if(a>4 | ++b>10 && a>0)  
    {
        System.out.print("stuff");    
    }
    System.out.print(b);
    

    The output to that is stuff10

    This way, regardless of one side being true or not, they're both still evaluated.

    The same thing goes for && and &

提交回复
热议问题