Controlling Program Flow: Use the Conditional Ternary Operator

What is it?

The conditional ternary operator is a shorthand way to write an if-else statement. It allows testing a condition in a single line, and returns a value based on the condition's result. The conditional operator is represented by the ? and : symbols and has the syntax:

condition ? value_if_true : value_if_false

Where,

  • condition: A boolean value or an expression that evaluates to a boolean value.
  • value_if_true: The value to return if the condition is true.
  • value_if_false: The value to return if the condition is false.



How to use it

Using the conditional ternary operator is simple and straightforward. Here's an example:

#include <iostream>

using namespace std;

int main() {

    int num1 = 10;
    int num2 = 20;
    
    string result = (num1 > num2) ? "num1 is greater" : "num2 is greater";
    
    cout << result << endl;
    
    return 0;
}

In the above code, we have two variables num1 and num2 containing integer values. We then use the conditional operator to compare the values of num1 and num2. If num1 is greater than num2, we store the string "num1 is greater" in the result variable. Otherwise, we store the string "num2 is greater". Finally, we print the value of the result variable.


Output:

num2 is greater




Use the ternary operator to check if a and b are equal or not. It should output either "Equal" or "Not Equal".