Minimal evaluation
From Free net encyclopedia
Template:Programming evaluation
Minimal evaluation or short circuit evaluation is an evaluation strategy in which an expression is only evaluated until the point where its final value is known. In some cases, it is not necessary to evaluate all the parts of an expression. Consider the following example using the C programming language:
int a = 0; if (a && myfunc(b)) { do_something(); }
In this example minimal evaluation guarantees that myfunc(b)
is never called. This is because a
evaluates to false, and false AND q evaluates to false for any value of q. This feature permits two useful programming constructs. Firstly, if the first sub-expression checks whether an expensive computation is needed and the check evaluates to false, one can eliminate expensive computation in the second argument. Secondly, it permits a construct where the first expression guarantees a condition without which the second expression may cause a runtime error, such as in the following C code where minimal evaluation prevents a null pointer dereference:
int is_three_chars_long(const char *p) { return (p != NULL) && (strlen(p) == 3); }
It is worth noting that these expressions may be considered a more compact way of expressing a nested branch or sequence of branches. For example:
if (cond_a && expensive_or_dangerous_cond_b) { branch_0 } else { branch_1 }
becomes (through logical and expansion)
if (cond_a) { if (expensive_or_dangerous_cond_b) { branch_0 } else { branch_1 } } else { branch_1 }
If code duplication is an issue, a more involved translation stores the result of the decision in a variable, as in:
int branch; if (cond_a) { if (expensive_or_dangerous_cond_b) { branch = 0; } else { branch = 1; } } else { branch = 1; } if (branch == 0) { branch_0 } else { branch_1 }
A compiler using the common subexpression elimination and constant propagation optimizations might generate the same code for all three versions.
Minimal evaluation can also be used to conditionally execute some code for side effects, as in the common Perl idiom:
some_condition or die; # Abort execution if some_condition is false