The ternary operator in C++ is a concise way to perform a conditional evaluation (also known as the conditional operator).
It is suitable for simplifying assignments based on a condition, offering a more compact alternative to the classic if-else structure.
If you want to learn more, check out the Introduction to Programming Course
Basic Syntax
The ternary operator in C++ follows this basic syntax:
condition ? true_expression : false_expression
- Condition: A boolean expression that evaluates to true (
true) or false (false). - True Expression: The value or expression returned if the condition is true.
- False Expression: The value or expression returned if the condition is false.
Basic Example
Suppose we want to determine if a number is even or odd and store the result in a variable called resultado. We can use the ternary operator to do this more compactly.
#include <iostream>
#include <string>
int main() {
int number = 10;
std::string result = (number % 2 == 0) ? "even" : "odd";
std::cout << "The number is " << result << std::endl;
return 0;
}
In this code, the ternary operator evaluates if numero % 2 == 0 (i.e., if the number is even). If the condition is true, resultado is set to "par"; if false, it is set to "impar". This approach reduces the need for a more extensive if-else structure.
Nesting the Ternary Operator
The ternary operator can be nested to handle multiple conditions.
#include <iostream>
#include <string>
int main() {
int number = 10;
std::string result = (number > 0) ? "positive" :
(number < 0) ? "negative" : "zero";
std::cout << "The number is " << result << std::endl;
return 0;
}
Here,
- It first evaluates if
numerois greater than 0 - If true,
resultadois set to"positivo" - If false, it evaluates if the number is less than 0
- If this is also false,
resultadois set to"cero"
Excessive nesting can affect code readability. So don’t overuse it.
Practical Examples
Compare Two Numbers and Determine the Largest
To compare two numbers and determine which is larger, we can use the ternary operator instead of a more extensive if-else structure.
#include <iostream>
int main() {
int a = 5;
int b = 8;
int greater = (a > b) ? a : b;
std::cout << "The greater number is " << greater << std::endl;
return 0;
}
In this example, mayor is assigned the value of a if a is greater than b; otherwise, it is assigned the value of b.
Value Assignment
The ternary operator is useful for assigning a value based on a simple condition in a single line of code.
#include <iostream>
#include <string>
int main() {
int age = 20;
std::string category = (age >= 18) ? "adult" : "minor";
std::cout << "The person is " << category << std::endl;
return 0;
}
Here, categoria is set to "adulto" if edad is greater than or equal to 18; otherwise, it is set to "menor de edad".
Return Value in Methods
The ternary operator can also be used to determine a method’s return value based on a condition.
#include <iostream>
#include <string>
std::string getGreeting(bool isFormal) {
return isFormal ? "Good morning, sir/madam" : "Hello";
}
int main() {
bool isFormal = true;
std::cout << getGreeting(isFormal) << std::endl;
return 0;
}
In this case, the function obtenerSaludo returns "Buenos días, señor(a)" if esFormal is true; otherwise, it returns "Hola".
These examples illustrate how to use the ternary operator to simplify code. It is not always the best option for all situations, especially if the logic is complex. In such cases, if-else structures may offer better clarity.
