The conditional operator is called the ternary operator because it involves three operands. - C++ Operator

C++ examples for Operator:Conditional Operator

Introduction

Suppose you want to assign the value of the greater of the two to a third variable, c. The following statement will do this:

c = a > b ? a : b;           // Set c to the higher of a and b

The assignment statement is equivalent to the if statement:

if(a > b) {
  c = a;
} else {
  c = b;
}

Using the conditional operator to select output.

Demo Code

#include <iostream>

int main()//ww  w  . j a  v  a 2 s.  c  o m
{
  int mice {};               // Count of all mice
  int brown {};              // Count of brown mice
  int white {};              // Count of white mice

  std::cout << "How many brown mice do you have? ";
  std::cin >> brown;
  std::cout << "How many white mice do you have? ";
  std::cin >> white;

  mice = brown + white;

  std::cout << "You have " << mice
            << (mice == 1 ? " mouse " : " mice ")
            << "in total." << std::endl;
}

Result


Related Tutorials