C programming - ternary operator
The ternary operator in C programming is a conditional operator that takes three operands. It is also known as the conditional operator or the conditional expression. The general syntax of the ternary operator is:
expression1 ? expression2 : expression3
where expression1
is the condition to be evaluated, expression2
is the value to be returned if the condition is true, and expression3
is the value to be returned if the condition is false.
Here is an example of using the ternary operator:
#include <stdio.h> int main() { int num = 5; int result; result = (num % 2 == 0) ? 0 : 1; printf("result = %d\n", result); return 0; }
In this example, we declared an integer variable num
and initialized it with the value 5. We used the ternary operator to check if num
is even or odd. If num
is even, the value of result
will be 0. Otherwise, the value of result
will be 1.
The output of the program will be:
result = 1
The ternary operator is useful when we need to make a decision based on a condition, and return different values based on the outcome of the condition. It can be used in place of an if-else
statement in some cases, which can make the code more concise and easier to read. However, it is important to use the ternary operator judiciously, as it can make the code harder to understand if it is used excessively.