Conditional operator or Ternary operator in C programming language

The conditional operator consists of two symbols: the mark (?) and the colon, (:).

Let us examine the ternary operator through an example. This program reads two integers and displays the value of the larger of the two. If they are equal, then naturally either of them will be printed.

#include<stdio.h>
void main() 
{
int i, j, larger;
printf("Input two integers: ");
scanf("%d %d", &i, &j);
larger = i > j ? i : j;
printf("The larger of the two is %d\n", larger);
} 

The statement that uses the conditional operator is:

larger = i > j ? i : j;

It has three components; the expression i > j before the question mark, and the variables i and j after it, one on each side of the ‘:’. We shall first see a sample run of the above program, and then analyse what the conditional operator does.

Input two integers: 34 45

The larger of the two is 45

Let us now see what the conditional statement does.

First, the expression before? (which is i > j) is evaluated. In the above case, the expression is false

Since the expression before ? is false, the whole expression involving the conditional operator evaluates to the expression following the colon (:). In this case, this is just the variable j

Here is one more test run.

Input two integers: 5 -1

The larger of the two is 5

In this case, the conditional statement operates as follows:

* as before, the expression before? (which is i>j) is evaluated. The expression is true, since i is 5 and j is -1.

* since the expression before? Is true, the whole expression involving the conditional operators evaluates to the expression before the colon (:).