Instead of writing longer if and else conditional statements, We have ternary operator to minimize the size of Program. This ternary operator is used by most of the programmer, prefer to use the ternary operator for decision making. Ternary operator is basically a minimized version of if-else statement which is efficient to use.
There are also some limitations with Ternary operator is we can use it only to replace if-else statement. But if we have to use multiple if-else-if the this is not better option.
Lets see some more details about ternary operator with examples below.
In C, Ternary operator takes 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
Syntax of ternary operators in C
[c]testCondition ? expression1 : expression 2;[/c]
(age >= 60) ? printf(“Senior Citizen”) : printf(“Not a Senior Citizen”);
Example 1 : Print Smallest Among Three in C using Ternary Operator
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.
[c]
int a = 20, b = 30, c;
if (a < b) {
c = a;
}
else {
c = b;
}
printf(“%d”, c);
[/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.
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
[c]
int a = 20, b = 30, c;
c = (a < b) ? a : b;
printf(“%d”, c);
[/c]
Example 2 : If-else and corresponding its ternary operator
[c]int a = 5, b = 6, c;
if (a == 5) {
if (b == 6) {
c = 3;
} else {
c = 5;
}
} else {
c = 0;
}
printf (“%d\n”, c);
[/c]
And corresponding ternary operator
Here’s the code above rewritten using a nested ternary operator
[c]
int a = 5, b = 6, c;
ans = (a == 5 ? (b == 6 ? 3 : 5) : 0);
printf (“%d\n”, ans);
[/c]