Conditional Operator in C Language

This “Conditional Operator in C Language” post provides complete information about syntax of ternary operator, use of ternary operator in c with suitable examples.


 

Conditional operator:

  • It is a ternary operator

  • It performs operation on 3 operands.

  • The operator is  “?:”

  • In Conditional operator if “Condition is true” then executes <expression1> else executes <expression2>

 

Syntax :  

        <condition> ? <expression1> : <expression2>

 

Example :
 (a>b) ? (c=25) : (c=45); 

 

Can be written as :
c = (a>b) ? 25 : 45;

 

Program that finds biggest among two numbers :
    #include<stdio.h>
    main()
    {
        int a,b;
        printf(“enter two numbers : \n”);
        scanf(“%d%d”,&a, &b) ;
        (a>b) ? printf(“a is big”) : printf(“b is big”);
    }

    #include<stdio.h>
    main()
    {
        int a,b,big;
        printf(“enter two numbers : \n”);
        scanf(“%d%d”,&a, &b) ;
        big = a>b ? a : b ;
        printf(“big one is : %d\n”,big);
    }

We can define One conditional operator inside another conditional operator depends on logic requirement.

Syntax-1: Condition ? Expression-1 : Condition ? Expression-1 : Expression-2 ;
Syntax-1: Condition ? Condition ? Expression-1 : Expression-2 : Expression-2  ;

 

Codes to describe above Syntax :
 

    #include<stdio.h>
    main()
    { 
        int res = 10>20 ? 10 : 20>30 ? 20 : 30;
        printf(“res : %d\n”,res);
    }

    #include<stdio.h>
    main()
    { 
        int a=20,b=30,c=10;
        int res = a>b ? a>c ? a : c : b>c ? b : c;
        printf(“res : %d\n”,res);
    }

Share this