Conditional Operator in the C Computer Language
Part 20 of the Complete C Course
Foreword: Conditional Operator in the C Computer Language
By: Chrysanthus Date Published: 4 Jun 2024
Introduction
int func(int a, int b) {
if (a > b) {
return 50;
} else {
return 40;
}
}
Note that there is no stand-alone final return statement in this function definition. If the function is called with func(2,1), then 50 will be returned. If it is called with func(1,2), then 40 will be returned. This function can be replaced with the conditional operation,
a > b ? 50 : 40
Note the use and positions of '?' and ':' . There are three operand expressions here, which are "a > b", 50 and 40. If the condition, "a > b" is true, then 50 is returned. Else if it is false, then 40 is returned.
The return value of the above function can be received by a variable (identifier), from the function call, as follows:
int z = func(a,b)
In a similar way, the returned value of the conditional operation can be received by a variable, z as follows:
int z = a > b ? 50 : 40
The following code prints out 50:
int a = 2;
int b = 1;
int z = a > b ? 50 : 40;
printf("%i\n", z);
The syntax of the conditional operation is:
condition ? expression : conditional-expression
The operation consists of '?' and ':' with three operands. Here, "expression" is the value returned when condition is true, and "conditional-expression" is the value returned when condition is false.