Ternary Operator

beginner c++11

C++ has a concise one-line if statement called the ternary operator (?:). The ternary operator is useful when expressing clear and simple if statements and it is equivalent to using if-else, just shorter. The syntax is expression ? true_case : false_case. For example:

#include <iostream>

int32_t max(int32_t a, int32_t b) {
  if (a > b) {
    return a;
  } else {
    return b;
  }
}

int32_t max_ternary(int32_t a, int32_t b) {
  return a > b ? a : b;
}

int main() {
  std::cout << max(1, 2) << "\n";
  std::cout << max(42, 7) << "\n";
  
  std::cout << max_ternary(1, 2) << "\n";
  std::cout << max_ternary(42, 7) << "\n";
}
2
42
2
42

For more C++ By Example, click here.