C++ offers a compact way to write if...else
statements using the ternary operator (? :
). This operator condenses decision-making logic into a single line, making code more readable and efficient.
How the Ternary Operator Works
Instead of writing a full if...else
statement, the ternary operator allows for a quick evaluation of a condition.
Syntax
C++
x
variable = (condition) ? expressionTrue : expressionFalse;
- If the condition is true, the expressionTrue is executed.
- If false, the expressionFalse runs instead.
Example: Traditional if...else
Statement
C++
using namespace std;
int main() {
int temperature = 30;
if (temperature < 25) {
cout << "It's a cool day.";
} else {
cout << "It's a warm day.";
}
return 0;
}
Example: Using the Ternary Operator
The same logic written more concisely:
C++
using namespace std;
int main() {
int temperature = 30;
string weatherStatus = (temperature < 25) ? "It's a cool day." : "It's a warm day.";
cout << weatherStatus;
return 0;
}