Conditional (Ternary) Operator in c++ [? :]

Conditional (Ternary) Operator in c++ [? :]


The condional operator can often be used instead of the if else statement. Since it is the only operator that requires three operands in c++, it is also called ternary operator.

For example, consider the assignment statement :
x = y > 3 ? 2 : 4;
If y is greater than 3 then 2 will be assigned to variable x or else the value 4 will be assigned to x.

/* A simple c++ program example to demonstrate the use of ternary operator. */


// Program 1


#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First" << setw (3) << ": ";
    cin >> first;

    cout << "Second" << setw (2) << ": ";
    cin >> second;

    string message = first > second ? "first is greater than second" :
                                "first is less than or equal to second";

    cout << message << endl;

    return 0;
}


Compare the above "Program 1" and below "Program 2" with "Program 2" and "Program 3" of Selection Statement (if-else if-else) in c++ respectively, for better understanding.

/* A c++ program example to demonstrate the use ternary operator.*/


// Program 2


#include <iostream>
#include <iomanip>

using namespace std;

int main ()
{
    int first, second;

    cout << "Enter two integers." << endl;

    cout << "First" << setw (3) << ": ";
    cin >> first;

    cout << "Second" << setw (2) << ": ";
    cin >> second;

    string message = first > second ? "first is greater than second" :
                                first < second ? "first is less than second" :
                                "first and second are equal";

    cout << message << endl;

    return 0;
}

Check out this stream