Conditional Operator in C
The conditional operator is also known as a ternary operator. The conditional statements are the decision-making statements which depends upon the output of the expression. It is represented by two symbols, i.e., '?' and ':'.
As conditional operator works on three operands, so it is also known as the ternary operator.
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else' statement is also a decision-making statement.
Syntax
Expression1? expression2: expression3;
Examples of Conditional Operator
Basic Example
#include <stdio.h>
int main()
{
int a = 10, b = 20;
int max = (a > b) ? a : b; // Conditional operator
printf("Max value is: %d\n", max);
return 0;
}
Output
Nested Conditional Operator
The conditional operator can be nested, allowing you to make multiple decisions in a single expression. This can be useful for complex conditions, but it can also make the code harder to read.
Example
#include <stdio.h>
int main()
{
int a = 10, b = 20, c = 30;
int max = (a > b) ? ((a > c) ? a : c) : ((b > c) ? b : c); // Nested conditional operator
printf("Max value is: %d\n", max);
return 0;
}
Output
Conditional Operator with Multiple Expressions
While the conditional operator typically returns a value, you can also use it with expressions that execute more complex operations.
Example
#include <stdio.h>
int main()
{
int a = 10, b = 20;
(a > b) ? printf("a is greater\n") : printf("b is greater\n"); // Conditional operator with expressions
return 0;
}
Output
Advantages of Conditional Operator
- Conciseness: The conditional operator is a more compact alternative to using an
if-else
statement, making the code shorter and more readable for simple conditions. - Performance: In some cases, using the conditional operator can lead to more optimized code, though the difference is often negligible.
Disadvantages of Conditional Operator
- Readability: While it is concise, using the conditional operator excessively or in complex conditions can make the code harder to read and maintain.
- Nested Usage: Overusing nested conditional operators can result in difficult-to-understand code, making debugging harder.