C: Conditional/Ternary Operator
The conditional operator is a shorthand for a simple if-else statement and is written with the ternary operator “? :
”. It operates on three operands and hence is also known as a ternary operator.
The syntax for the conditional operator is
condition? expression1 : expression2
The first operand condition
is a Boolean expression, and is evaluated first. If condition
evaluates to true, the second operand expression1
is evaluated, becoming the value of the conditional expression. If not, the third operand expression2
is evaluated.
In the program below, if the entered integer n
is greater than 0, the first operand (n > 0)
is evaluated as true, and hence the second operand +
is returned and assigned to operator
. Else, the third operand -
is assigned to operator
.
#include <stdio.h>
main() {
int n;
char operator;
printf("Integer: ");
scanf("%d", &n);
operator = ((n > 0)? '+':'-');
printf("%d is a %c ve number", n, operator);
}