Conditional operator in C

Conditional operator is a ternary operator used to evaluate an expression based on some condition. It is a replacement of short if...else statement.

Syntax of conditional operator

<conditional-expression> ? <true-expression> : <false-expression>
  • It accepts three operands, conditional-expression, true-expression and false-expression.
  • The conditional-expression is followed by ? symbol, followed by true-expression. true-expression is followed by : symbol and false-expression.
  • If conditional-expression is true then true-expression gets evaluated otherwise false-expression. In no case both the expressions are evaluated.

The above conditional expression is equivalent to -


if(conditional-expression)
{
    // true-expression
}
else
{
    // false-expression
}

Example program of 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;

    /*
     * If (num > num2) then
     *    assign num1 to max
     * else
     *    assign num2 to max
     */
    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 false-expression gets evaluated assigning 20 to max.

Practice to learn - Conditional operator programming exercises and solutions

Important note: Always feel free to transform single if...else statement to conditional operator expression, if it makes your code more readable and clear. However, it is never recommended to transform a nested if...else...if or ladder if...else statement to conditional operator expression.

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>