Short Hand if...else
(Ternary Operator) in C++
C++ provides a shorthand way to write simple if...else
statements using the ternary operator ?:
. It's useful for concise conditional assignments.
Syntax of the Ternary Operator
variable = (condition) ? expression_if_true : expression_if_false;
Example: Using the Ternary Operator
#include <iostream>
int main() {
int age = 17;
std::string status;
status = (age >= 18) ? "Adult" : "Minor";
std::cout << "You are an " << status << "." << std::endl;
return 0;
}
Explanation: The ternary operator checks if age
is greater than or equal to 18. Since it's not, status
is assigned "Minor".
Key Takeaways
- The ternary operator provides a concise syntax for simple
if...else
statements. - Enhances code readability for straightforward conditions.
- Use parentheses for clarity when using the ternary operator.