Conditional operator (ternary operator)
suggest changeEvaluates its first operand, and, if the resulting value is not equal to zero, evaluates its second operand. Otherwise, it evaluates its third operand, as shown in the following example:
a = b ? c : d;
is equivalent to:
if (b)
a = c;
else
a = d;
Its form is condition ? value_if_true : value_if_false. Each branch can be an expression. The if/else sketch above is not a complete equivalent: the conditional operator yields a value, converts the second and third operands to a common type, and evaluates only the selected operand.
int x = 5;
int y = 42;
printf("%i, %i\n", 1 ? x : y, 0 ? x : y); /* Outputs "5, 42" */
The conditional operator can be nested. For example, the following code determines the bigger of three numbers:
big= a > b ? (a > c ? a : c)
: (b > c ? b : c);
The following example writes even integers to one file and odd integers to another file:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *even, *odds;
int n = 10;
int k = 0;
even = fopen("even.txt", "w");
odds = fopen("odds.txt", "w");
if (even == NULL || odds == NULL) {
perror("fopen");
if (even != NULL) {
fclose(even);
}
if (odds != NULL) {
fclose(odds);
}
return EXIT_FAILURE;
}
for (k = 1; k < n + 1; k++)
{
k%2==0 ? fprintf(even, "\t%5d\n", k)
: fprintf(odds, "\t%5d\n", k);
}
fclose(even);
fclose(odds);
return 0;
}
The conditional operator associates from right to left. Consider the following:
exp1 ? exp2 : exp3 ? exp4 : exp5
As the association is from right to left, the above expression is evaluated as
exp1 ? exp2 : ( exp3 ? exp4 : exp5 )