C Ternary Operator

C Ternary Operator allows to choose one of the two values based on a condition.

In this tutorial, we will learn its syntax, usage and nesting of ternary operators with examples.

Flow Diagram of C Ternary Operator

Following is the flow diagram of Ternary Operator in C.

ADVERTISEMENT
C Ternary Operator

Syntax of C Ternary Operator

The syntax of C Ternary Operator is

x = condition ? value_1 : value_2;

So, ternary operator has three operands. From the above syntax, they are condition, value_1 and value_2.

where

condition is a boolean value or an expression that evaluates to boolean value. The condition is generally formed using comparison operators and logical operators.

If the condition is true, Ternary Operator returns value_1. If the condition is false, Ternary Operator returns value_2. The returned value can be stored in a variable, say x.

value_1 and value_2 could be a value or an expression that evaluate to a value.

Ternary Operator can be interpreted using if-else statement as below.

if (condition) {
    x = value_1;
} else {
    x = value_2;
}

Example 1 – C Ternary Operator

In the following example, we use Ternary Operator to find the maximum of two integers. The condition is if value in a is greater than that of b. If yes, we assign a to the variable max, else we assign b. After executing this ternary operator, variable max will end up with largest of a and b.

C Program

#include <stdio.h>

void main() {
    int a = 10, b = 20;
    int max = (a > b) ? a : b;
    printf("%d", max);
}

Output

20

Example Ternary Operator with Expression for Values

In the following example program, for ternary operator, we provide expressions for the value to be returned when the condition is true or false.

C Program

#include <stdio.h>

void main() {
    int a = 5;
    int b = 2;
    int c = (a > b) ? (a*a + 2) : (b*9);
    printf("%d", c);
}

Output

27

Nested Ternary Operator

We know that Ternary Operator is an expression that returns a value. So, for the values (second and third operands), you can give a Ternary Operator.

In the following example, we shall use nested Ternary Operator to find the maximum of three numbers.

C Program

#include <stdio.h>

void main() {
    int a = 5;
    int b = 2;
    int c = 7;
    int max = (a > b) ? ((a>c) ? a : c) : ((b > c) ? b : c);
    printf("%d", max);
}

Output

7

Conclusion

In this C Tutorial, we learned what a Ternary Operator is in C programming language, how its execution happens, and how it works with example programs.