When to prefer `and` over `andalso` in guard tests

前端 未结 4 843
别那么骄傲
别那么骄傲 2021-02-02 08:48

I am curious why the comma ‹,› is a shortcut for and and not andalso in guard tests.

Since I\'d call myself a “C native” I fail to see any shor

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 09:27

    To delve into the past:

    • Originally in guards there were only , separated tests which were evaluated from left-to-right until either there were no more and the guard succeeded or a test failed and the guard as a whole failed. Later ; was added to allow alternate guards in the same clause. If guards evaluate both sides of a , before testing then someone has gotten it wrong along the way. @Kay's example seems to imply that they do go from left-to-right as they should.

    • Boolean operators were only allowed much later in guards.

    • and, together with or, xor and not, is a boolean operator and was not intended for control. They are all strict and evaluate their arguments first, like the arithmetic operators +, -, * and '/'. There exist strict boolean operators in C as well.

    • The short-circuiting control operators andalso and orelse were added later to simplify some code. As you have said the compiler does expand them to nested case expressions so there is no performance gain in using them, just convenience and clarity of code. This would explain the resultant code you saw.

    • N.B. in guards there are tests and not expressions. There is a subtle difference which means that while using and and andalso is equivalent to , using orelse is not equivalent to ;. This is left to another question. Hint: it's all about failure.

    So both and and andalso have their place.

提交回复
热议问题