Short-Circuit Evaluation
" Short-Circuit Evaluation " 在一般Programming Language書中解釋:
" A short-circuit evaluation of an expression is one in which the result is determined without
evaluating all of the operands and/or operators. "
簡單來說,決定一個expression的結果,不需要估計到所有的operands及operators。
" Short-Circuit Evaluation " 有人稱為 " Lazy Evaluation Exploitation "。
" Short-Circuit Evaluation " 主要是針對AND(&&)及OR(||),首先列出AND及OR的真值表(truth table):
A | B | A && B |
False | False | False |
False | True | False |
True | False | False |
True | True | True |
A | B | A || B |
False | False | False |
False | True | True |
True | False | True |
True | True | True |
考慮 A
&& B時,當A為False時,A
&& B 的結果即為False
,B的結果不會影響到A
&& B的結果。
考慮 A || B時,當A為True時,A
|| B 的結果即為True
,B的結果不會影響到A
|| B的結果。
以上的條件在估計時,不需要估計到B值,就能決定出Boolean
expression的結果。
這就稱作為" Short-Circuit
Evaluation " 或 "
Lazy Evaluation Exploitation "。
測試程式是否如以上所說:
#include <stdio.h>
int expr(int
dummy)
{
printf("%d execute!\n",dummy);
return 1;
}
int main()
{
if ( 1 && expr(1) )
;
if ( 0 && expr(2) )
;
if ( 0 || expr(3) )
;
if
( 1 || expr(4) )
;
return 0;
}
看程式結果之後,就能夠證實"
Short-Circuit Evaluation " 。
Written By James , 2004/09/24 下午 09:52:03