What is wrong with the short circuit logic in this Java code?

后端 未结 9 1098
挽巷
挽巷 2021-01-18 01:58

Why doesn\'t func3 get executed in the program below? After func1, func2 doesn\'t need to get evaluated but for func3, shouldn\'t it?

if (func1() || func2()          


        
9条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-18 02:26

    You're using a short-circuited or. If the first argument is true, the entire expression is true.

    It might help if I add the implicit parentheses that the compiler uses

    Edit: As Chris Jester-Young noted, this is actually because logical operators have to left-to-right associativity:

    if (func1() || (func2() && func3()))
    

    After func1 returns, it becomes this:

    if (true || (func2() && func3()))
    

    After evaluating the short-circuited or, it becomes:

    if (true)
    

提交回复
热议问题