Conditional Operator in C

The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'. As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a decision-making statement.

Syntax

                
Expression1? expression2: expression3;  
       
            

Examples of Conditional Operator

Basic Example

        
#include <stdio.h>
int main() 
{
    int a = 10, b = 20;
    int max = (a > b) ? a : b;  // Conditional operator

    printf("Max value is: %d\n", max);
    return 0;
}
        
    

Output

Max value is: 20

Nested Conditional Operator

The conditional operator can be nested, allowing you to make multiple decisions in a single expression. This can be useful for complex conditions, but it can also make the code harder to read.

Example

        
#include <stdio.h>
int main() 
{
    int a = 10, b = 20, c = 30;
    int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c);  // Nested conditional operator

    printf("Max value is: %d\n", max);
    return 0;
}
        
    

Output

Max value is: 30

Conditional Operator with Multiple Expressions

While the conditional operator typically returns a value, you can also use it with expressions that execute more complex operations.

Example

        
#include <stdio.h>
int main() 
{
    int a = 10, b = 20;
    (a > b) ? printf("a is greater\n") : printf("b is greater\n");  // Conditional operator with expressions

    return 0;
}
        
    

Output

b is greater

Advantages of Conditional Operator

Disadvantages of Conditional Operator