Ternary Operator
Many if-else statements only choose a value. If the score is 50 or more, the result is "pass". Otherwise, it is "fail". For this, C++ has a shorter form: the ternary operator, ? :.
#include <iostream>
#include <string>
using namespace std;
int main() {
int score = 62;
string result = (score >= 50) ? "pass" : "fail";
cout << result << "\n";
return 0;
}
Output:
pass
Read ? as "then" and : as "otherwise". So the line says: is the score 50 or more? Then use "pass", otherwise use "fail". C++ checks the condition, and the whole expression becomes one of the two values. Here score >= 50 is true, so result gets "pass".
The same code with if-else is longer, and you must create the variable before the if:
int score = 62;
string result;
if (score >= 50) {
result = "pass";
} else {
result = "fail";
}
cout << result << "\n";
Output:
pass
The name "ternary" means "made of three parts". It is the only C++ operator that takes three parts: the condition, the value for true, and the value for false.
Picking one of two numbers
A common use is picking the smaller or larger of two numbers:
int a = 9;
int b = 4;
int smaller = (a < b) ? a : b;
cout << smaller << "\n";
Output:
4
a < b is false, so the expression becomes b, which is 4.
Inside a cout line
You can also use the ternary directly inside cout, where an if cannot go. Put the whole ternary in parentheses. Without them, the program does not compile.
int age = 15;
cout << (age >= 18 ? "adult" : "minor") << "\n";
Output:
minor
Keep the ternary for short and simple choices. If you need more than one condition, or each side needs several steps, use a normal if-else. It is easier to read.
In the exercise, use the ternary operator to find the larger of two numbers.