C++에서 조건부 연산자 사용

Jinku Hu 2023년10월12일
  1. C++에서 조건부 연산자를rvalue표현식으로 사용
  2. 조건부 연산자를 C++에서lvalue표현식으로 사용
C++에서 조건부 연산자 사용

이 기사에서는 C++ 조건부 연산자를 활용하는 방법을 설명합니다.

C++에서 조건부 연산자를rvalue표현식으로 사용

일반적인 산술, 논리 및 할당 연산자와 별도로 C++는 몇 가지 특수 연산자를 제공하며 그중 하나는 조건부 삼항 연산자입니다. 삼항은 연산자가 세 개의 피연산자를 취함을 의미합니다. if-else문과 유사하게 작동하므로 조건부 연산자라고합니다. 연산자는E1 ? E2 : E3, 여기서 첫 번째 피연산자는if조건으로 처리 될 수 있으며 이는 평가되고bool값으로 변환됩니다.

bool값이true이면 다음 표현식 (E2)이 평가되고 부작용이 발생합니다. 그렇지 않으면 세 번째 표현식 (E3)이 부작용과 함께 평가됩니다. 이 연산자를rvalue표현식으로 활용하여 변수에 조건부로 값을 할당 할 수 있습니다. 다음 예제 코드에서는 사용자 입력에서 정수를 읽고 조건 연산자에서E1피연산자를 나타내는 비교 표현식input > 10을 평가합니다. 변수n에는E1이 참인 경우에만input값이 할당됩니다.

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main() {
  int input;

  cout << "Enter a single integer: ";
  cin >> input;
  int n = input > 10 ? input : 10;

  cout << "n = " << n << endl;

  return EXIT_SUCCESS;
}

출력:

Enter a single integer: 21
n = 21

조건부 연산자를 C++에서lvalue표현식으로 사용

또는 삼항 연산자를lvalue표현식으로 활용하여 할당 작업이 수행되는 변수 이름을 조건부로 선택할 수 있습니다. 변수 이름은 두 번째 및 세 번째 피연산자로만 지정합니다. 그러나 일반적으로 외부 부작용이있는cout과 같은 표현식을 지정할 수 있습니다. 이러한 효과는 평소와 같이 실행됩니다.

#include <iostream>
#include <string>

using std::cin;
using std::cout;
using std::endl;
using std::string;

int main() {
  int input;

  cout << "Enter a single integer: ";
  cin >> input;
  int n = input > 10 ? input : 10;

  cout << "n = " << n << endl;

  int m = 30;
  (n == m ? n : m) = (m * 10) + 2;

  cout << "m = " << m << endl;

  return EXIT_SUCCESS;
}

출력:

Enter a single integer: 21
n = 21
m = 302

삼항 연산자의 또 다른 사용 사례는class정의에 있습니다. 다음 코드 샘플은 단일 링크 목록의 노드와 유사한MyClass구조에 대한 재귀 생성자를 구현 한 이러한 시나리오를 보여줍니다. 이 경우 생성자 호출을next인수로 호출되는 두 번째 피연산자로 지정하고node.nextfalse값으로 평가 될 때까지 반복 호출 스택을 계속했습니다. 후자는node.next포인터가nullptr인 경우에만 해당됩니다.

#include <iostream>
#include <string>

struct MyClass {
  MyClass* next;
  int data;

  MyClass(const MyClass& node)
      : next(node.next ? new MyClass(*node.next) : nullptr), data(node.data) {}

  MyClass(int d) : next(nullptr), data(d) {}

  ~MyClass() { delete next; }
};

int main() { return EXIT_SUCCESS; }
작가: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook

관련 문장 - C++ Operator