To: J3 J3/18-239 From: Dan Nagle Subject: logical short-circuits Date: 2018-August-08 I Introduction There has been some demand for, and some other programming languages have a way that guarantees, a way to evaluate logical operands in a user-specified order. This paper focuses on the and-then and or-else operators, as tools for programmers to specify an order of evaluation of logical operands. II Use-cases The poster-child use-case is something like if( I <= NMAX .and. A(I) > 0.0 )then where the intention is to evaluate A(I) only when I is in-bounds. Similarly, the snippet logical, optional, intent( in) :: flag ... if( present( flag) .and. flag )then where the intention is to check the value of flag only after its presence is known. Fortran allows a processor to skip evaluation of portions of an expression when the value of the expression can be deduced otherwise. But the compiler is not required to do so. Many compilers are more aggressive at eliminating code at higher levels of optimization. This leads to the situation where a code may appear to be correct at -On, n > N, but not at lower levels. This can be confusing and frustrating. While RTFM is a correct response, a more helpful response is to provide the programmer with a way to sequence the evaluation of the operands. Nesting if-blocks has been seen as labor-intensive, especially in cases where the if-block is large (as may be true in older codes). III What I have in mind I propose adding an .ANDTHEN. operator and an .ORELSE. operator. The .ANDTHEN. operator has the same truth table as .AND. but guarantees that its right operand is not evaluated when the left operand is false. The .ORELSE. operator has the same truth table as .OR. but guarantees that its right operand is not evaluated when the left operand is true. While there has been some support for similar ideas previously, progress has always ended during the discussion of operator precedence. I believe the operator precedence should be lowest. I have two reasons: 1. andthen / orelse are "bigger" operations than and and or, so their precedence should be lower 2. andthen / orelse involve, possibly, a jump over code. The code subject to such jumping should be clear in the source (for example, within parenthesis). However, this is likely worth a straw vote. Straw Vote: Should the precedence of .ANDTHEN. and .ORELSE. be Lowest, after all other operations The same as .AND. and .OR., respectively Undecided IV (Rough) Requirements Two new logical operators are added, .ANDTHEN. and .ORELSE. These operators require logical operands and produce a logical result. They have the same truth-table as .AND. and .OR., respectively. The .ANDTHEN. operator guarantees that it does not evaluate its right-hand operand when its left-hand operand is false. The .ORELSE. operator guarantees that it does not evaluate its right-hand operand when its left-hand operand is true. Operator precedence is as determined by the straw vote above.