The ternary operator helps you choose between two values quickly in one line. It makes simple decisions easy to write and read.
0
0
Ternary operator in C++
Introduction
When you want to assign a value based on a condition without writing a full if-else statement.
When you want to print different messages depending on a condition in a short way.
When you want to return one of two values from a function based on a quick check.
Syntax
C++
condition ? value_if_true : value_if_false;
The condition is checked first.
If the condition is true, the expression returns value_if_true, otherwise it returns value_if_false.
Examples
This sets
max to the bigger of a and b.C++
int a = 10, b = 20; int max = (a > b) ? a : b;
This checks if
num is even and sets isEven accordingly.C++
bool isEven = (num % 2 == 0) ? true : false;
This prints "Pass" if
score is 50 or more, otherwise "Fail".C++
std::cout << ((score >= 50) ? "Pass" : "Fail") << std::endl;
Sample Program
This program asks for your age and uses the ternary operator to decide if you are an Adult or a Minor, then prints the result.
C++
#include <iostream> #include <string> int main() { int age; std::cout << "Enter your age: "; std::cin >> age; std::string category = (age >= 18) ? "Adult" : "Minor"; std::cout << "You are an " << category << "." << std::endl; return 0; }
OutputSuccess
Important Notes
The ternary operator is best for simple decisions. For complex logic, use if-else statements for clarity.
Both value_if_true and value_if_false should be of compatible types.
Summary
The ternary operator is a short way to choose between two values based on a condition.
It uses the syntax: condition ? value_if_true : value_if_false.
Use it to make your code shorter and easier to read for simple choices.