Node:and_then, Next:AnsiChar, Previous:and then, Up:Reference
operator and_then (operand1, operand2: Boolean) = Result: Boolean;
The and_then short-circuit logical operator performs the same
operation as the logical operator and. But while the ISO standard
does not specify anything about the evaluation of the operands of and
- they may be evaluated in any order, or not at all - and_then has
a well-defined behaviour: It evaluates the first operand. If the result is
False, and_then returns False without evaluating the
second operand. If it is True, the second operand is evaluated and
returned.
Since the behaviour described above is the most efficient way to implement
and, GPC by default treats and and and_then exactly the
same. If you want, for some reason, to have both operands of and
evaluated completely, you must assign both to temporary variables and then
use and - or and_then, it does not matter.
and_then is an ISO 10206 Extended Pascal extension.
Some people think that the ISO standard requires both operands of
and to be evaluated. This is false. What the ISO standard
does say is that you cannot rely on a certain order of
evaluation of the operands of and; in particular things like
the following program can crash according to ISO Pascal, although
they cannot crash when compiled with GNU Pascal running in default
mode.
program AndBug;
var
p: ^Integer;
begin
New (p);
ReadLn (p^);
if (p <> nil) and (p^ < 42) then { This is NOT safe! }
WriteLn ('You''re lucky. But the test could have crashed ...')
end.
program And_ThenDemo;
var
p: ^Integer;
begin
New (p);
ReadLn (p^);
if (p <> nil) and_then (p^ < 42) then { This is safe. }
WriteLn (p^, ' is less than 42')
end.