Conditional operator in C

Conditional operator is a ternary operator. It is used to evaluate an expression based on some condition.

Syntax of conditional operator
<conditional-expression> ? <expression1> : <expression2>

If the conditional-expression is true (1) then expression1 gets evaluated otherwise expression2. But in no case both the expressions are evaluated.

Example program to demonstrate conditional operator

Consider the below program to find maximum between two numbers using conditional operator

#include <stdio.h>

int main()
{
    int num1 = 10;
    int num2 = 20;

    int max = (num1 > num2) ? num1 : num2;

    printf("Maximum is %d.", max);

    return 0;
}

In the above program prints Maximum is 20.. Since the condition (num1 > num2) is false therefore expression2 gets evaluated assigning 20 to max.

Write your doubts or suggestion. I will try my best to help. You must escape source code before commenting. To format your source code paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>