논리 연산자
논리 연산자 (Logical operators)
논리 연산자는 피연산자에 표준 불 대수(Boolean algebra) 연산을 적용해요. !(NOT), &&(AND), ||(OR) 세 가지가 있는데, 그중 &&와 ||는 **단락 평가(short-circuit evaluation)**라는 특별한 동작을 가져요. 왼쪽 결과만으로 답이 정해지면 오른쪽은 아예 평가하지 않는 거예요. 이 페이지에서 각 연산자의 타입과 반환 값을 정리해 볼게요.
본문
논리 연산자는 피연산자에 표준 불 대수 연산을 적용해요.
| 연산자 | 연산자 이름 | 예 | 결과 |
|---|---|---|---|
! |
논리 NOT | !a |
a의 논리 부정 |
&& |
논리 AND | a&&b |
a와 b의 논리 AND |
|| |
논리 OR | a||b |
a와 b의 논리 OR |
논리 NOT (Logical NOT)
논리 NOT 표현식의 형태는 다음과 같아요.
| 형태 |
|---|
! 표현식 |
논리 NOT 연산자는 타입 int를 가져요. 표현식이 0과 같지 않은 값으로 평가되면 그 값은 0이고, 표현식이 0과 같은 값으로 평가되면 그 값은 1이에요 (그래서 !E는 (0==E)와 같아요).
#include <stdbool.h>
#include <stdio.h>
#include <ctype.h>
int main(void)
{
bool b = !(2 + 2 == 4); // not true
printf("!(2+2==4) = %s\n", b ? "true" : "false");
int n = isspace('a'); // non-zero if 'a' is a space, zero otherwise
int x = !!n; // "bang-bang", common C idiom for mapping integers to [0,1]
// (all non-zero values become 1)
char *a[2] = {"non-space", "space"};
puts(a[x]); // now x can be safely used as an index to array of 2 strings
}
출력:
!(2+2==4) = false
non-space
논리 AND (Logical AND)
논리 AND 표현식의 형태는 다음과 같아요.
| 형태 |
|---|
lhs && rhs |
여기서
| lhs | - | 어떤 스칼라 타입의 표현식 |
|---|---|---|
| rhs | - | 어떤 스칼라 타입의 표현식. lhs가 0과 같지 않게 비교될 때만 평가돼요 |
논리 AND 연산자는 타입 int를 갖고, lhs와 rhs가 둘 다 0과 같지 않게 비교되면 값 1을 가져요. 그 외의 경우(하나라도 둘 다 0과 같게 비교되면) 값 0을 가져요.
lhs 평가 후에 시퀀스 포인트가 있어요. lhs의 결과가 0과 같게 비교되면, rhs는 전혀 평가되지 않아요 (이른바 단락 평가(short-circuit evaluation)).
#include <stdbool.h>
#include <stdio.h>
int main(void)
{
bool b = 2 + 2 == 4 && 2 * 2 == 4; // b == true
1 > 2 && puts("this won't print");
char *p = "abc";
if (p && *p) // common C idiom: if p is not null
// AND if p does not point at the end of the string
{
// (note that thanks to short-circuit evaluation, this
// will not attempt to dereference a null pointer)
// ... then do some string processing
}
}
논리 OR (Logical OR)
논리 OR 표현식의 형태는 다음과 같아요.
| 형태 |
|---|
lhs || rhs |
여기서
| lhs | - | 어떤 스칼라 타입의 표현식 |
|---|---|---|
| rhs | - | 어떤 스칼라 타입의 표현식. lhs가 0과 같게 비교될 때만 평가돼요 |
논리 OR 연산자는 타입 int를 갖고, lhs나 rhs가 0과 같지 않게 비교되면 값 1을 가져요. 그 외의 경우(둘 다 0과 같게 비교되면) 값 0을 가져요.
lhs 평가 후에 시퀀스 포인트가 있어요. lhs의 결과가 0과 같지 않게 비교되면, rhs는 전혀 평가되지 않아요 (이른바 단락 평가).
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
int main(void)
{
bool b = 2 + 2 == 4 || 2 + 2 == 5; // true
printf("true or false = %s\n", b ? "true" : "false");
// logical OR can be used simialar to perl's "or die", as long as rhs has scalar type
fopen("test.txt", "r") || printf("could not open test.txt: %s\n", strerror(errno));
}
가능한 출력:
true or false = true
could not open test.txt: No such file or directory
더 알아보기
- 논리 연산자의 결과는 보통 **조건문(
if/while)**과 비교 연산자와 함께 흐름 제어에 쓰여요. &&/||의 단락 평가와 시퀀스 포인트는 평가 순서 문서에서 이어져요.- cppreference의 Logical operators 원문에서 표준 절 번호(C11/C99/C89)를 더 확인할 수 있어요.