J3/04-410r1 Date: November 9, 2004 Subject: ANDTHEN and ORELSE pseudo-functions From: Dick Hendrickson Reference: J3/04-390, 04-193, 04-357R1 Basic functionality: Guarantee short-circuit evaluation of AND and OR operations. There has been considerable e-mail discussion of a way to perform short-circuiting of tests, usually to allow writing things simply and to avoid common user errors. Various forms of an .ANDTHEN. operator have been proposed. A canonical example is I > 0 .AND. I < 10 .ANDTHEN. A(I) /= 0 the .ANDTHEN. guarantees that A(I) won't be referenced if I is out of range. Paper 04-390 provides more rational. Much of the discussion has centered on the priority of the new operators. Should they be: highest, lowest, the same or different, or the same as .AND. and .OR.? Reasonably compelling arguments have been made for all of the possibilities. This proposal replaces the operators with functions and thus resolves the priority issue. The functions are called pseudo-functions to emphasize that they are different from normal functions. An alternate name could be "selector functions". They can be used anyplace that an ordinary function can be used, including in declarations, if they follow whatever normal rules apply to that use. The functionality guarantees that the argument expressions will be evaluated in the listed order, left to right, one at a time, and that argument evaluation will stop when the function result can be determined, and that exceptions and side effects won't occur for un-required evaluations. They effectively require short-circuiting. Detailed Specification: Add two new elemental pseudo-functions ANDTHEN (A1 ,A2 [, A3, ...AN] ) ORELSE (A1 ,A2 [, A3, ...AN] ) Arguments: A1, ...AN Logical, of any kind, they must be conformable The arguments are evaluated in sequence, left to right, one at a time. Evaluation of the arguments stops when ANDTHEN encounters a FALSE value, ORELSE encounters a TRUE value, or when the last argument has been evaluated. The result of the function is the value of the last argument actually evaluated. (This is equivalent to the AND or OR, respectively, of all of the evaluated arguments.) Entities in arguments which are not evaluated need not be defined, present, allocated, evaluatable, etc, nor may the processor generate any side-effects or exceptions from these arguments. Note that for elemental usage, different result elements will usually evaluate different sets of arguments. Examples: IF ( ANDTHEN(I > 0, I<10, A(I) > 0 ) ) A(I) = log(A(I)) WHERE ( ANDTHEN( X > 0.0, log(X) < Tol) ) ... IF ( ANDTHEN( PRESENT(X), X==0) ) Print *, "X must not be zero!" The function can be usefully combined with the "IF" function from paper 383R1 Local_value = IF ( ANDTHEN ( present(X), X /= 0.0), X, 1.0) ) REAL :: Temp ( IF ( ANDTHEN (present(x), size(x)>100), size(x), 100) )