Instead of writing longer if and else conditional statements most of the programmer prefer to use the ternary operator for decision making.

In c programming language ternary operator take three arguments:

  • The first argument is for comparison
  • The second argument is the result which will be print/return when the condition is true
  • The third argument is the result which will be print/return when the condition is false

In simple words, we can say that a ternary operator is the shortest form of an if-else statement. Below are the example of if-else and after that, we will also see we can convert that if-else into the ternary operator.

int a = 20, b = 30, c;
if (a < b) {
c = a;
}
else {
c = b;
}
printf("%d", c);

In the above example/code, you can see that it has taken almost 8 lines but using a ternary operator we can write that code in just 3 lines.

syntax of Ternary Operator

condition ? if_true : if_false

Above syntax means if_true will be output if the condition is met, and if_false will be output when the condition does not met.

Below is the conversion into ternary operator for the above if-else example

int a = 20, b = 30, c;
c = (a < b) ? a : b;
printf("%d", c);

One More Example of if-else and corresponding its ternary operator

int a = 5, b = 6, c;
if (a == 5) {
if (b == 6) {
c = 3;
} else {
c = 5;
}
} else {
c = 0;
}
printf ("%d\n", c);

And corresponding ternary operator

Here’s the code above rewritten using a nested ternary operator:

int a = 5, b = 6, c;
ans = (a == 5 ? (b == 6 ? 3 : 5) : 0);
printf ("%d\n", c);