Conditional/Ternary Operator - Devbhoomi

FREE JOB ALERT & ONLINE TUTORIALS

Hot

Post Top Ad

Sunday 5 November 2017

Conditional/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 <stdio.h>

    int main()
    {
    int a = 5;
    char c;

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

    //Example 2
    // condition ? ( condition ? expression1 : expression2 ) : expression2
    c = (a < 10) ? ((a < 5) ? 's' : 'l') : ('L');
    printf("\nC = %c",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.

No comments:

Post a Comment

Post Top Ad