C++/공부내용
C++ Tutorial - Conditions / Short Hand If Else
HappyFrog
2022. 6. 14. 18:38
If... Else 짧게 작성하기 (3중 연산자)
if else를 짧게 쓸 수 있는 것이 있는데 3개의 연산되는 함수로 이루어져 있어 3중 연산자로 알려진 것입니다. 이것은 여러 줄의 코드를 단 한줄로 대체할 수 있습니다. 또한 if else 선언문을 간단하게 대체할 때 사용됩니다.
문법
variable = (condition) ? expressionTrue : expressionFalse;
if... else 사용:
예시
#include <iostream>
using namespace std;
int main() {
int time = 20;
if (time < 18) {
cout << "Good day.";
}
else {
cout << "Good evening.";
}
}
당신은 이것을 간단하게 작성할 수 있습니다.
예시
#include <iostream>
using namespace std;
int main() {
int time = 20;
string result = (time < 18) ? "Good day." : "Good evening.";
cout << result;
}