Ternary Operator

Shashwat Raj
1 min readAug 12, 2019

--

The operator which uses three operands or variable is known as Ternary Operator. There is only one Ternary Operator in C.

It is known as Conditional Operator.

Syntax

Condition (Exp1) ? Condition_if_true (Exp2) : Condition_if_false (Exp3)

It uses an operator that takes three arguments. The first argument is a condition, the second is the result if condition is true, and the third is the result if condition is false.

Ternary operator is a?b:c it says that the condition a is true b will be executed else c will be executed.

Ternary operator is a shortened way of writing an if-else statement. Programmers use ternary operators in C for decision making in place of conditional statements if and else.

Finding the greatest No. using if-else
Finding the greatest No. using Ternary operator

Return Type:

The ternary operator has return type. The return type depends on Condition_if_true(Exp2), and convertibility of Condition_if_false(Exp3) into Condition_if_true(Exp2) as per usual conversion rules. If they are not convertible, the compiler throws an error.

Program Compiles without any error

The return type of ternary expression is expected to be float (as that of exp2) and exp3 ( int type) is implicitly convertible to float.

Program will not compile

The compiler is unable to find return type of ternary expression or implicit conversion is unavailable between exp2 (char array) and exp3 (float).

--

--

Shashwat Raj

Honours Computer Science Student & Enthusiast working with Python | Data Science | Machine Learning | Artificial Intelligence | Web Development