What is Ternary Operator in C++: Simple Explanation and Example
ternary operator in C++ is a compact way to write an if-else statement in a single line. It uses the syntax condition ? expression1 : expression2, where it returns expression1 if the condition is true, otherwise expression2.How It Works
The ternary operator works like a quick decision maker. Imagine you want to choose between two options based on a yes/no question. Instead of writing a full if-else block, the ternary operator lets you write this choice in one line.
It checks the condition. If the condition is true, it picks the first option (expression1); if false, it picks the second option (expression2). This is like asking, "Is it raining?" If yes, take an umbrella; if no, wear sunglasses.
This operator is called "ternary" because it uses three parts: the condition, the true result, and the false result.
Example
This example shows how to use the ternary operator to check if a number is even or odd and print the result.
#include <iostream> #include <string> int main() { int number = 7; std::string result = (number % 2 == 0) ? "Even" : "Odd"; std::cout << "The number " << number << " is " << result << ".\n"; return 0; }
When to Use
Use the ternary operator when you need a simple choice between two values based on a condition. It makes your code shorter and easier to read for small decisions.
For example, setting a variable based on a quick check, choosing a message to display, or returning a value from a function without writing multiple lines.
Avoid using it for complex conditions or multiple nested choices, as that can make your code hard to understand.
Key Points
- The ternary operator is a shorthand for simple if-else statements.
- It uses three parts: condition, true expression, and false expression.
- It returns a value based on the condition.
- Best for simple, quick decisions in code.
- Can improve readability when used properly.