Ternary operators are a shorthand way of writing an if-else statement. They are also known as the conditional operator. Ternary operators are used to assign a value to a variable based on a condition.
condition ? value_if_true : value_if_falseThe condition is the expression that is evaluated. If it is true, the operator returns the value_if_true expression; otherwise, it returns the value_if_false expression.
int a = 10;
int b = 5;
int max_value = (a > b) ? a : b; // max_value will be 10In this example, the ternary operator (a > b) ? a : b evaluates to a because the condition (a > b) is true. Therefore, max_value is assigned the value of a, which is 10.
int a = 10;
int b = 5;
cout << ((a > b) ? "a is greater than b" : "b is greater than a") << endl;In this example, the ternary operator (a > b) ? "a is greater than b" : "b is greater than a" evaluates to "a is greater than b" because the condition (a > b) is true. Therefore, the message "a is greater than b" is outputted to the console.
int a = 10;
int b = 5;
int max_value = (a > b) ? a : ((a < b) ? b : a);
// max_value will be 10In this example, the nested ternary operator ((a < b) ? b : a) is used to compare a and b again in case a is not greater than b. If a is less than b, the operator returns b, and if a is greater than or equal to b, the operator returns a. Therefore, max_value is assigned the value of a, which is 10.
Ternary operators can make code shorter and more concise, but they should be used sparingly and only when the expression being evaluated is simple and easy to read.
I hope this helps you to understand ternary operators in C++!