우연히 페이스북에서 생활코딩의 한 게시물을 보게 되었다.
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 evalutation이란, 산술 연산과 같이 간편하게 이뤄지는 것이 아니다.
그보다는 control flow로써, 프로그램 내에서 각각의 명령이나 함수가 호출되는 순서와 같다.
그래서 명령형 프로그래밍 언어에서는 Sequence point 라는 것을 이용하여 Short-circuit evalutation가 가능하게 만들었다.
https://en.wikipedia.org/wiki/Sequence_point
Sequence point란, 해당 지점 이전의 모든 연산이 완료되었음을 보증하는 것이다.
C계열 언어나 Java에서 사용하는 ; 세미콜론을 생각하면 된다.
여기서 &&, || 도 Sequence point 이다.
그래서 아래의 수식에서
(++i || ++j && ++k)
++i 가 True 이므로, || 연산자는 Short-circuit evalutation을 통해 뒤의 연산을 하지 않는다
'개발' 카테고리의 다른 글
IntelliJ에서 JUnit, AssertJ 프로젝트 생성하기 (0) | 2022.06.27 |
---|---|
[Java] HashMap 내부 코드에 존재하는 transient 키워드 (0) | 2022.06.23 |
[Spring] 싱글톤 패턴의DIP 위반과 만족 (0) | 2022.02.26 |
[Java] Queue에서 poll()과 remove() 중 무엇을 선택해야 할까? (0) | 2022.01.23 |
코드 실행시간 측정하기 (Java, Python, C, C++) (0) | 2022.01.10 |