C++ ternary operator

A ternary operator is some operation operating on 3 inputs. It's a shortcut for an if-else statement, and is also known as a conditional operator.

Syntax :

    (condition) ? expression1 : expression2

If condition is true expression1 is evaluated else expression2 is evaluated. Expression1/Expression2 can also be further conditional expression.
Example :

#include <iostream>
using namespace std;
int main()
{
    int a = 5;
    char c;

    //Example 1
    // condition ? expression1 : expression2
    c = (a < 10) ? 'S' : 'L';
    cout<<"C = "<<c;

    //Example 2
    // condition ? ( condition ? expression1 : expression2 ) : expression2
    c = (a < 10) ? ((a < 5) ? 's' : 'l') : ('L');
    cout<<"\nC = "<<c;

    return 0;
}

Output :
    C = S
    C = l
Explanation :
//Example 1
    c = (a < 10) ? 'S' : 'L';
This means, if (a < 10), then c = S else c = L
//Example 2
    c = (a < 10) ? ((a < 5) ? 's' : 'l') : ('L');
This means, if (a < 10), then check one more conditions if(a < 5), then c = s else l, else c = L.

0 Comments