마음의 안정을 찾기 위하여 - Short-circuit evaluation
2037432
115
267
관리자새글쓰기
태그위치로그방명록
별일없다의 생각
dawnsea's me2day/2010
색상(RGB)코드 추출기(Color...
Connection Generator/2010
최승호PD, '4대강 거짓말 검...
Green Monkey**/2010
Syng의 생각
syng's me2DAY/2010
천재 작곡가 윤일상이 기획,...
엘븐킹's Digital Factory/2010
Short-circuit evaluation
My Library | 2007/11/28 09:15
출처 : http://en.wikipedia.org/wiki/Short_circuit_evaluation


&& 연산자는 왼쪽이나 오른 쪽 항 중에 하나가 거짓이면 결과값이 무조건 거짓입니다.
|| 연산자는 두 항 중에 하나가 참이면 결과값은 무조건 참이죠.
그래서 ||나 &&의 왼쪽 항 만으로 TRUE, FALSE가 판별가능한 경우에는 오른쪽 항을 계산하지 않습니다. 이것을 short circuit rule이라고 부릅니다.  (연산의 횟수가 줄어들기 때문에 속도가 빨라짐)


Short-circuit evaluation or minimal evaluation denotes the semantics of some boolean operators in some programming languages in which the second argument is only executed or evaluated if the first argument does not suffice to determine the value of the expression: when the first argument of and evaluates to false, the overall value must be false; and when the first argument of or evaluates to true, the overall value must be true. In some programming languages (Lisp), the usual boolean operators are short-circuit. In others (C, Ada), both short-circuit and standard boolean operators are available.

The short-circuit operator x Sand y is equivalent to the conditional expression if x then y else false; x Sor y is equivalent to if x then true else y.

Typically short-circuit operators are, in effect, control structures rather than simple arithmetic operators, as they are not strict. However ALGOL 68 used "proceduring" to achieve user defined short-circuit operators & procedures.

In loosely-typed languages which have more than the two truth-values True and False, short-circuit operators may return the last evaluated subexpression, so that x Sand y is actually equivalent to if x then x else y (without actually evaluating x twice). This is called "Last value" in the table below.

Boolean operators in various languages
Language Standard operators Short-circuit operators Value
Ada and , or and then , or else Boolean
ALGOL68 and/&/∧ , or/∨ andf , orf - user defined bool
C , Java & , | && , || Boolean
C++ & , bitand , | , bitor && , and , || , or Boolean
Javascript & , | && , || Last value
Lisp none and , or Last value
Perl & , | && , and , || , or Last value
Python & , | and , or Last value
Visual Basic And , Or AndAlso , OrElse Boolean


Example
Consider the following example using the C programming language:

   int a = 0;
   if (a && myfunc(b)) {
       do_something();
   }

In this example, short-circuit evaluation guarantees that myfunc(b) is never called. This is because a evaluates to false. 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 IsThreeCharsLong(const char *p) {
     return (p != NULL) && (strlen(p) == 3);
   }

Despite these benefits, minimal evaluation may cause problems for programmers who do not realize (or forget) it is happening. For example, in the code

   if (expressionA && myfunc(b)) {
       do_something();
   }

if myfunc(b) is supposed to perform some required operation regardless of whether do_something() is executed, such as allocating system resources, and expressionA evaluates as false, then myfunc(b) will not execute, which could cause problems. Some programming languages, such as Java, have two operators, one that employs minimal evaluation and one that does not, to avoid this problem.

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, consider the following block of code, when minimal evaluation is in use:

   if (CONDITION_A && CONDITION_B) {
       TRUE_BRANCH
   } else {
       FALSE_BRANCH
   }

becomes (through logical AND expansion)

   if (CONDITION_A) {
       if (CONDITION_B) {
           BOTH_TRUE
       } else {
           B_FALSE
       }
   } else {
       A_FALSE
   }

Note that, due to the nature of the boolean logic involved, both the A_FALSE and B_FALSE code branches are represented by the single FALSE branch in the first example. However, following the more verbose second example does, at least, have one possible advantage ? different code can be executed depending upon which condition, if any, is FALSE. Note however that if both conditions are false, only A_FALSE will be executed, and not B_FALSE.

A compiler using the common subexpression elimination and constant propagation optimizations might generate the same code for all such versions.

Minimal evaluation can also be used to conditionally execute some code for side effects, as in the common Perl idioms:

 some_condition or die;    # Abort execution if some_condition is false
 some_condition and die;   # Abort execution if some_condition is true


ALGOL 68
The original language of the 1968 Final Report differs in syntax from the 1973 Revised Report. The original had the feature of proceduring, i.e. coercing the value of a term into a procedure which evaluates the term. Proceduring effectively can make evaluations lazy. The most useful application could have been the short-circuited evaluation of boolean operators.

Examples of user defined operators:

op andf = (bool a, proc bool b)bool: if a then b() else a fi; ? b is only evaluated, if a is true.  ?
op orf  = (bool a, proc bool b)bool: if a then a else b() fi; ? b is only evaluated, if a is false. ?


Hence before the 1973 Revised Report, the programmer could decide to have the arguments of an operator (and indeed a procedure) evaluated serially instead of collaterally.

As defined in ALGOL 68, it did not work as expected. Most implementations emulate the Short-circuit behaviour for this special case by an extension of andf/orf or andth/orel to the "standard preclude".


2007/11/28 09:15 2007/11/28 09:15
이 글의 관련글 이글의 태그와 관련된 글이 없습니다.
Article tag list Go to top
View Comment 2
Trackback URL :: 이 글에는 트랙백을 보낼 수 없습니다
From. Rhio.kim 2007/12/03 20:21
답글달기삭제
제 타이틀을 깔끔하게 정리해 주셨네요.. ^-^
델파이에서도 저렇게 쓰는 경우가 있나요??
From. 복분자주(그리움) 2007/12/04 08:50
답글달기삭제
Function Data(Var Val : Integer) : Boolean;
Begin
Inc(Val);

Result := True;
End;

Var
iData : Integer;
begin
iData := 0;

If (TRUE Or Data(iData)) Then Begin
showmessage('TRUE : ' + inttostr(idata));
End
else showmessage('FALSE : ' + inttostr(idata));
end;

위와 같이 했을때 iData의 값은 "0"으로 나오네요.

델파이도 다른 언어와 마찬가지로 왼쪽항의 결과에 따라 오른쪽 항의 연산 유무를 결정하는 것 같네요.

"If (FALSE Or Data(iData)) Then Begin"로 하게 되면, iData의 값은 "1"....
PREV : [1] : NEXT
 
 
 
 
: [1] ... [644][645][646][647][648][649][650][651][652] ... [860] :
«   2022/08   »
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      
전체 (860)
출판 준비 (0)
My-Pro... (41)
사는 ... (492)
블로그... (22)
My Lib... (32)
게임 ... (23)
개발관... (3)
Smart ... (1)
Delphi (75)
C Builder (0)
Object... (0)
VC, MF... (9)
Window... (1)
Open API (3)
Visual... (0)
Java, JSP (2)
ASP.NET (0)
PHP (4)
Database (12)
리눅스 (28)
Windows (23)
Device... (1)
Embedded (1)
게임 ... (0)
Web Se... (2)
Web, S... (19)
잡다한... (5)
프로젝트 (0)
Personal (0)
대통령... (9)
Link (2)