![]() |
VOOZH | about |
The conditional operator in C is kind of similar to the if-else statement as it follows the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible. It is also known as the ternary operator in C as it operates on three operands.
The conditional operator can be in the form
variable = Expression1 ? Expression2 : Expression3;
Or the syntax can also be in this form
variable = (condition) ?Expression2 : Expression3;Or syntax can also be in this form
(condition) ? (variable = Expression2) : (variable = Expression3);It can be visualized into an if-else statement as:
if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}
Since the Conditional Operator '?:' takes three operands to work, hence they are also called ternary operators.
Note: The ternary operator have third most lowest precedence, so we need to use the expressions such that we can avoid errors due to improper operator precedence management.
The working of the conditional operator in C is as follows:
To understand the working better, we can analyze the flowchart of the conditional operator given below.
m is greater than n that is 5 > 4
The year 1900 is not a leap year
The conditional operator or ternary operator in C is generally used when we need a short conditional code such as assigning value to a variable based on the condition. It can be used in bigger conditions but it will make the program very complex and unreadable.