C++ Ternary operator
When crafting an if-else statement in C++, the ternary operator offers a convenient shortcut. It has three operands and is also known as the conditional operator. The ternary operator has the following syntax:
condition ? expression1 : expression2;
Here, the “condition” is evaluated first, and if it is true, the operator returns the value of “expression1”. If the condition is false, it returns the value of “expression2”.
Let’s consider an example to understand this better:
int x = 10;
int y = 20;
// using ternary operator to find the maximum value
int max = (x > y) ? x : y;
In this example, we’ll use the ternary operator to obtain the largest value that can be found between the two variables “x” and “y.” In this instance, the condition is “x > y,” and if it is true, the value of “x” is returned; else, the value of “y” is returned.
Since “y” in this instance exceeds “x,” its value is returned, and the variable “max” is given the value of 20.
Example:
#include <iostream>
#include <string>
int main() {
int age = 25;
std::string status = (age >= 18) ? "Adult" : "Minor";
std::cout << "Age: " << age << ", Status: " << status << std::endl;
age = 16;
status = (age >= 18) ? "Adult" : "Minor";
std::cout << "Age: " << age << ", Status: " << status << std::endl;
return 0;
}
Output:
Age: 25, Status: Adult
Age: 16, Status: Minor
In this example, the variable “age” is initially declared and given the value of 25. Then, if the age is 18 or older, we use the ternary operator to assign the string “Adult” to the variable “status,” and if it is younger than 18, we assign the string “Minor.” Using std::cout, we print the age and status.
The process is then repeated with the age set to 16, producing the new age and status.