Benefits of using short-circuit evaluation

后端 未结 15 1540
余生分开走
余生分开走 2020-12-05 16:23
boolean a = false, b = true;
if ( a && b ) { ... };

In most languages, b will not get evaluated because a is fals

15条回答
  •  无人及你
    2020-12-05 16:53

    I honestly wouldn't worry about it. Testing a boolean is really fast. Short-circuiting only gets interesting / useful when the second expression has side effects:

    if ( ConfirmAction() && DestroyAllData() )
       Reboot();
    

    ...or depends on the first test:

    if ( myDodgyVar != null && myDodgyVar.IsActive() )
       DoSomethingWith(myDodgyVar);
    

提交回复
热议问题