11
OctTernary Operator in C: Ternary Operator vs. if...else Statement
Ternary Operator in C: An Overview
In the Operators in C, we saw the definition, syntax, and one basic example of theternary
operator in C. In this tutorial, we will get into the Ternary
operator in detail. Join us in our C Tutorial to examine the fundamental ideas and real-world uses of ternary operators in C programming.Assign the ternary operator to a variable
We saw the syntax of aternary
operator:testexpression? expression1 : expression2;
In the above syntax, we can assign the expression of the ternary
operator to a variable like this:
testcondition = condition? expression1 : expression2;
Here, if the condition
results in true
, expression1
will get assigned to the variable, testcondition
. If false
, expression2
will get assigned to the variable.
Example
#include <stdio.h>
int main()
{
int a = 5;
int b = 10;
int max = (a > b) ? a : b;
printf("The maximum value is: %d\n", max);
return 0;
}
test-condition
, “a>b
” is checked. If it evaluates to true
, the value of a
will be printed else the value of b
will be printed.Read More - Top 50 Mostly Asked C Interview Questions
Output
The maximum value is: 10
Ternary Operator Vs. if...else Statement in C
Theternary
operator may sometimes be used to replace multiple lines of code with a single line. Many a time, it is used to replace simple if-else
statement. It enhances the code readability by reducing the length of your program.Example
#include <stdio.h>
int main()
{
int num=3;
if (num % 2 == 0) {
printf("Even Number");
}
else {
printf("Odd Number");
}
return 0;
}
The above code checks whether a number is odd or even with the help of an if-else
statement.
We can use the ternary
operator to perform the same operation.
#include <stdio.h>
int main() {
int num = 3;
(num % 2 == 0) ? printf("Even Number") : printf("Odd Number");
return 0;
}
If we compare the above two codes, we can find that the code using the ternary
operator looks more readable and short as compared to the one using if-else
.
If you want to use a single if-else
statement to check any condition, you can go for the ternary
operator. However, it is totally up to you what to select.