BLOG DETAILS

Nesting of conditional operator in C/C++ Language

  • By Suresh Kulahry
  • |
  • November 28, 2018

The conditional operator is also known as "Ternary Operator". The conditional operator contains a condition followed by two statements or values. If the condition is true, the first statement is executed, otherwise the second statement is executed.

Syntax:

            CONDITION ? EXPRESSION-1 : EXPRESSION-2;

Example:

            a==0 ? printf("A is Zero") : printf("A is Not Zero");

Note:

The additional use of conditional operator is "SELECTIVE ASSIGNMENT".

Programming Examples

void main()
{
        int a,b,max;
        clrscr();
        printf("Enter Two Number");
        scanf("%d%d",&a,&b);
        max=a>b?a:b;//Selective Assignment.
        printf("Maximum among %d and %d is %d",a,b,max);
}

We know that the general form of the conditional operator is condition ? true part : false part. This form can also be interpreted as:

If condition then statement else statement

The nesting of conditional operator generally in two forms.

  • Nesting inside false part/else part.
    • Condition ? True Part : Condition ? True Part : False Part;
  • Nesting inside true part/if part.
    • Condition ? Condition ? True Part : False Part : False Part;