C Language | Flow Control | Conditional Operator
This article explains the conditional operator, which selects an expression according to a condition. Unlike an if statement, the conditional operator chooses one of two expressions.
Ternary Operator
Most C operators are unary operators with one operand or binary operators with two operands. The conditional operator ? : is a ternary operator with three operands.
The conditional operator expresses behavior similar to an if statement in a single expression. It is suitable for small branches. For example, if n is not 0, assign x to z; otherwise, assign y.
Conditional Operator
condition ? expression1 : expression2
If the condition is true, the operator selects expression1 and returns its value. Otherwise, it selects expression2. To choose a value to assign to z, write:
z = n ? x : y;
If n is true, this expression assigns x to z. Otherwise, it assigns y. You can write the same logic with an if-else statement, but the conditional operator is more concise.
Code 1
#include <stdio.h>
int main() {
int iVariable;
printf("Please input a number 0 or some else>");
scanf("%d" , &iVariable);
printf("An input value is %s.\n" , iVariable ? "True" : "False");
return 0;
}
This program receives 0 or another value from the user and displays whether it is true or false. The expression iVariable ? "True" : "False" returns "True" if iVariable is true and "False" otherwise. The %s conversion specifier in printf() displays the selected string.