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

后端 未结 9 1143
挽巷
挽巷 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条回答
  •  终归单人心
    2021-01-18 02:23

    Java functions are evaluated according to precedence rules

    because "&&" is of higher precendence than "||", it is evaluated first because you did not have any brackets to set explicit precedence

    so you expression of

    (A || B && C) 
    

    which is

    (T || F && F)
    

    is bracketed as

    (T || (F && F)) 
    

    because of the precedence rules.

    Since the compiler understands that if 'A == true' it doesn't need to bother evaluating the rest of the expression, it stops after evaluating A.

    If you had bracketed ((A || B) && C) Then it would evaluate to false.

    EDIT

    Another way, as mentioned by other posters is to use "|" and "&" instead of "||" and "&&" because that stops the expression from shortcutting. However, because of the precedence rules, the end result will still be the same.

提交回复
热议问题