Short Circuit Evaluation 개념 및 주의점 (단축 평가)

AND(&&) 연산자 혹은 OR(||) 연산자와 같은 논리 연산자, Logical Operator를 사용할 때, 굳이 모든 연산을 다하지 않더라도 결과를 알게 되는 경우가 있습니다.

하나라도 False를 만족하는 AND 연산자하나라도 True를 만족하는 OR 연산자의 경우입니다.

이처럼 앞 부분의 결과만으로 조건을 판단할 수 있을 때 뒷 부분은 생략하는 것을 Short Circuit Evaluation, 단락(단축) 평가라 합니다.

1
2
3
4
5
if(conditionA && conditionB)
// conditionA가 False인 경우 conditionB 검사없이 넘어감

if(conditionA || conditionB)
// conditionA가 True인 경우 conditionB 검사없이 넘어감

Short Circuit Evaluation은 아래와 같이 응용할 수 있습니다.

1
if (myStack.empty() || myStack.top() != num)

만약 myStack이 empty일때 top을 호출하게 되면 런타임 에러가 발생하게 됩니다.
하지만 위와 같이 empty를 먼저 검사하게되면 Short Circuit Evaluation에 의해 empty일 경우 top이 호출되지 않기 때문에 에러를 막을 수 있습니다.

사용시 주의점

앞 부분으로만 결과가 판단되는 경우에 뒷 부분의 구문은 실행되지 않습니다.

아래 예시 코드를 봅시다.

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
32
33
#include <iostream> 

bool LeftCondition(bool b) {
std::cout << "Left Condition Executed " << b << std::endl;
return b;
}

bool RightCondition(bool b) {
std::cout << "Right Condition Executed " << b << std::endl;
return b;
}

int main(void) {
std::cout << "# Case A (false && true) " << std::endl;
if (LeftCondition(false) && RightCondition(true)) {
// Left
}

std::cout << "# Case B (true && true) " << std::endl;
if (LeftCondition(true) && RightCondition(true)) {
// Left, Right
}

std::cout << "# Case C (false || true) " << std::endl;
if (LeftCondition(false) || RightCondition(true)) {
// Left, Right
}

std::cout << "# Case D (true || true) " << std::endl;
if (LeftCondition(true) || RightCondition(true)) {
// Left
}
}

Case A와 D같은 경우 Short Circuit Evaluation에 의해 Left 조건만 실행됩니다.
다시 말해, Right 함수가 호출이 되지 않을 때가 있습니다.
만약 Right 함수이 꼭 호출되어야 한다면 위와 같이 작성할 경우 문제가 되고, 원인 파악이 어렵습니다.
따라서 앞의 조건과 뒤의 조건을 모두 호출하려는 경우엔 코드를 다른 방식으로 작성하여야 합니다.

ref) https://en.wikipedia.org/wiki/Short-circuit_evaluation

Comments