조건 연산자
정의
- 조건문의 결과에 따라 대입할 값이나 실행할 수식을 선택할 수 있는 연산자
? 와 : 로 표현한다.
1
2
3
4
| expr1 ? expr2 : expr3
// expr1 : 조건식
// expr2 : 조건식이 참일 때의 값
// expr3 : 조건식이 거짓일 때의 값
|
예시
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| void conditional_operator(){
// 표준 형식
int a = 1;
int b = 2;
int max = a > b ? a : b;
println_int("the max is %d\n", max);
// 수식을 담는 경우
int c = 1;
int d = 2;
c > d ? d++ : c++;
printf("c's value : %d / d's value : %d", c, d);
}
|
1
2
| the max is 2 # b 의 값이 출력됨
c's value : 2 / d's value : 2 # c 가 증가됨
|
Reference
C 프로그래밍 (김형근, 곽덕훈, 정재화 공저)
C 프로그래밍 강의 (방송통신대 - 이병래)
Comments