본문 바로가기

개발

Short-circuit evaluation과 Sequence Point

우연히 페이스북에서 생활코딩의 한 게시물을 보게 되었다.

 

https://www.facebook.com/groups/174499879257223/?multi_permalinks=7441092495931222 

 

 

질문의 내용은 

 

int i = 1, j = 1, k = 1;

printf("%d\n", ++i || ++j && ++k);
printf("%d %d %d", i, j, k);

 

해당 코드의 결과값이

 

1

2 2 2

 

라고 생각하였는데

 

1

2 1 1

 

인 것이 이해가 가지 않는다는 것이었다

 

 

나도 처음에 코드만 봤을 때는

 

1

2 2 2

 

가 맞지 않나? 라고 생각했지만,

 

정답을 보고 나서는 아차! 싶었다

 

 

이 이유는 조금만 생각해본다면, 당연한 것이다

 

AND && 연산자와 OR || 연산자에 대해서 생각해보자

 

다음과 같은 논리 수식이 있다면 우리는 그 결과를 알 수 있을까?

 

False AND XXX

True OR XXX

 

정답을 알 수 있다

 

 

AND는 하나라도 False이면 False이고

 

OR은 하나라도 True라면, True이기 때문이다.

 

 

프로그래밍 언어에서는 Short-circuit evalutation이 이를 해결해준다.

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

 

Short-circuit evaluation - Wikipedia

Programming language construct Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if

en.wikipedia.org

 

 

그러나 사실 Short-circuit evalutation이란, 산술 연산과 같이 간편하게 이뤄지는 것이 아니다.

 

그보다는 control flow로써, 프로그램 내에서 각각의 명령이나 함수가 호출되는 순서와 같다.

 

 

그래서 명령형 프로그래밍 언어에서는 Sequence point 라는 것을 이용하여 Short-circuit evalutation가 가능하게 만들었다.

https://en.wikipedia.org/wiki/Sequence_point

 

Sequence point - Wikipedia

A sequence point defines any point in a computer program's execution at which it is guaranteed that all side effects of previous evaluations will have been performed, and no side effects from subsequent evaluations have yet been performed. They are often m

en.wikipedia.org

 

Sequence point란, 해당 지점 이전의 모든 연산이 완료되었음을 보증하는 것이다.

 

C계열 언어나 Java에서 사용하는 ; 세미콜론을 생각하면 된다.

 

여기서 &&, || 도 Sequence point 이다.

 

 

그래서 아래의 수식에서 

 

(++i || ++j && ++k)

 

++i 가 True 이므로, || 연산자는 Short-circuit evalutation을 통해 뒤의 연산을 하지 않는다