douyou7797
2017-08-15 17:33
浏览 65
已采纳

会在if语句中执行所有条件吗?

Example:

if function1(input) && function2(input) {}

In this case would function2(input) be executed if function1(input) returns false?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douliao8402 2017-08-15 17:43
    已采纳

    What you are asking about is called Short Circuiting, and yes, Go does it.

    In the language spec, it says that

    Logical operators apply to boolean values and yield a result of the same type as the operands. The right operand is evaluated conditionally.

    This means that, in your case, if function1 returned false, function2 would not be called.

    See an example for && here and for || here.

    打赏 评论
  • douji4948 2017-08-15 17:38

    No. Go uses standard conditional shortcut logic - the first false result in a string of && conditions will stop evaluation of further conditions (because it cannot yield a true result no matter what the other conditions are). Likewise, the first true result in a string of || conditions will stop evaluation because it cannot yield a false result no matter what the other conditions are.

    打赏 评论

相关推荐 更多相似问题