< Prev
Next >



Conditional Operator





C language provides a special kind of operator called - conditional operator. It is also called ternary operator because it has three operands, such as -




Syntax of conditional operator -


boolean-condition ? first expression : second expression;






Conditional operator example.


/* Conditional Operator Example */

#include<stdio.h>

int main()
{
int a=10, b=20;


int result =a>b ? 10 : 20;
printf("Result1 is %d \n", result);


result = a>b ? 10 : 100.50;
printf("Result2 is %d \n", result);


char ch = a>b ? 'y' : 'n';
printf("Result3 is %c \n", ch);


result = 100>=99 ? 100 : 99;
printf("Result4 is %d \n", result);

return 0;
}
Output
Result1 is 20
Result2 is 100
Result3 is n
Result4 is 100





  • The first expression of a conditional operator can be left blank

  • #include<stdio.h>
    
    int main()
    {
    int a=10, b=20;
    
    int result = a>b ? 0 : 10;
    printf("Result1 is %d \n", result);
    
    char ch = a < b ? : 'n'; 	/* Intentionally leaving the first expression */
    printf("Result2 is %c \n", ch);
    
    return 0;
    }
    
    


    Output-


    Result1 is 10
    Result2 is ☺

    In the last code, we have intentionally left out the first expression and the program has still compiled and executed successfully.




  • The second expression of a conditional operator cannot be left blank

  • #include<stdio.h>
    
    int main()
    {
    result = 9<2 ? 9 : ;
    printf("Result2 is %d \n", result);
    }


    Output-


    func41.c:5:20: error: expected expression before ';' token
     result = 9<2 ? 9 : ;
                        ^

    In the last code, we have intentionally left out the second expression and the compiler has thrown an error, complaining that the second expression is expected before semicolon.




  • An expression of a conditional operator can be a method call.
  • Any expression of a conditional operator could even be a call to a function but this function must return a value.

    #include<stdio.h>
    
    int main()
    {
    char fun(); /* function prototype declaration*/
    
    char result = 100>99? fun() : 'n'; /* Calling function fun() in the first expression */
    printf("Result is %c ", result);
    
    return 0;
    }
    
    
    char fun()
    {
    return 'y';
    }
    


    Output-


    Result is y

    In the last code, the first expression of the conditional operator is a call to a function fun(), which has returned us a char y.



    Please share this article -

    Facebook Google Pinterest Reddit Tumblr Twitter




    < Prev
    Next >
    < Logical Operators
    Array in C >
    Please subscribe our social media channels for notifications, we post a new article everyday.

    Decodejava Google+ Page Decodejava Facebook Page  DecodeJava Twitter Page

    Coming Next
    -
    C++ and Python

    Ad2