Short-Circuit Evaluation
In phix, all conditional expressions containing and or or operators use short-circuit evaluation. For example,
In general, whenever we have a condition of the form:
Similarly, with:
The expression B could contain something that would normally cause a run-time error. If phix skips the evaluation of B, then obviously that error does not occur. For instance:
This may look like sloppy coding, but in fact it often allows you to write something in a much simpler and more readable way. For instance:
Without short-circuit evaluation, a subscript out-of-bounds error would occur when s[i] is evaluated on the final iteration.
With short-circuiting, the loop terminates immediately when i<=length(s) becomes false.
Phix will not evaluate s[i]!='a' and will not evaluate s[i]!='A'.
No subscript error will occur.
if a<0 and b>0 then ...
If a<0 is false, then phix does not bother to test whether b is greater than 0.
It immediately assumes that the overall result is false. Similarly,
if a<0 or b>0 then ...
If a<0 is true, then phix immediately decides that the overall result is
false, without testing the value of b.
In general, whenever we have a condition of the form:
A and B
where A and B can be any two expressions, phix takes a short-cut when A is false and immediately
makes the overall result false, without even looking at expression B.
Similarly, with:
A or B
When A is true, phix skips the evaluation of expression B, and declares the result to be
true.
The expression B could contain something that would normally cause a run-time error. If phix skips the evaluation of B, then obviously that error does not occur. For instance:
if x!=0 and 1/x>10 then -- divide by zero error avoided
B could even contain uninitialized variables, out-of-bounds subscripts etc.
This may look like sloppy coding, but in fact it often allows you to write something in a much simpler and more readable way. For instance:
if atom(x) or length(x)=1 then
Without short-circuiting, you would have a problem when x was an atom,
since length is not defined for atoms. With short-circuiting, length(x)
will only be checked when x is a sequence. Similarly:
-- find ’a’ or ’A’ in s
i = 1
while i<=length(s) and s[i]!=’a’ and s[i]!=’A’ do
i += 1
end while
In this loop the variable i might eventually become (or initially be) greater than length(s). Without short-circuit evaluation, a subscript out-of-bounds error would occur when s[i] is evaluated on the final iteration.
With short-circuiting, the loop terminates immediately when i<=length(s) becomes false.
Phix will not evaluate s[i]!='a' and will not evaluate s[i]!='A'.
No subscript error will occur.