Ternary Operator

Many programming languages that use C-like syntax feature a ternary operator, ?: which defines a conditional expression.

The conditional expression written with the ternary operator "?:", provides an alternate way to write an if-else construct

In the expression

expr1 ? expr2 : expr3

the expression expr1 is evaluated first. If it is non-zero(true), then the expression expr2 is evaluated, and that is the value of conditional expression. Otherwise, expr3 is evaluated, and that is the value. Only one of expr2 and expr3 is evaluated.

 

The statements

if (a>b)

z = a;

else

z = b;

compute in z the maximum of a and b.

 

Thus, above expression can be written as

z = (a > b) ? a :b;

 

The ternary operator can be nested.

 

Example: display absolute value.

Example : ternary_absolute.c
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <stdlib.h>
 
int main() {
 
    int x, x_abs;
    printf("Enter a number : ");
    scanf("%d", &x);
    x_abs = (x < 0) ? -x : x;
    printf("The absolute value is : %d\n", x_abs);
    return 0;
}
 

 

Example: find maximum of 3 numbers

Example : ternary_max_among_3.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <stdlib.h>
 
int main() {
 
    int a, b, c;
    int max;
    printf("Enter first value : ");
    scanf("%d", &a);
    printf("Enter second value : ");
    scanf("%d", &b);
    printf("Enter third value : ");
    scanf("%d", &c);
    max = c > (a > b ? a : b) ? c : ((a > b ? a : b));
    printf("The maximum value is : %d\n", max);
    return 0;
}
Last modified: Tuesday, 3 April 2012, 06:57 AM