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的結果,不需要估計到所有的operandsoperators

" Short-Circuit Evaluation " 有人稱為  " Lazy Evaluation Exploitation "

" Short-Circuit Evaluation " 主要是針對AND(&&)OR(||),首先列出ANDOR的真值表(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時,當AFalse時,A && B 的結果即為FalseB的結果不會影響到A && B的結果。
考慮
A || B時,當ATrue時,A || B 的結果即為TrueB的結果不會影響到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

Catalog

Hosted by www.Geocities.ws

1