Explain Conditional Operator in C with Examples

Conditional operator is Ternary Operator that is it takes 3 operands. The general syntax of this operator is as:

expression1 ? expression2 : expression3;

Besides Operator Precedence and Associativity, It, like the logical operators, does exert some control on the order of evaluation of the entire expression. For example:

(number >=1000)? a + b + c : d + e + f;

Here in the above example, if (number >= 1000) is TRUE then result of whole expression is expression2 which is (a + b + c) and expression3 (d + e + f) is not evaluated at all. But if (number >= 1000) evaluates to FALSE then result of the entire expression is expression3 which is (d + e + f) and expression2 isn’t evaluated at all.

advertisements

Basically, conditional operator is same as if-else construct. We can rewrite the above conditional expression as:

if(expression1)
expression2;else
expression3;

Advantages of conditional operator over if-else construct:

Then what is the difference between conditional expression and if-else statement. Firstly, conditional expression is little bit more compact than if-else construct. For example:

Best Training

Testimonials

It was a wonderful course, a thorough study through the bits and pieces of Storage Devices and the other advancements in the SAN technology which was very informative for me. Well prepared slides, practical thoughts and fully interactive class.
— Milind - Microsoft

The depth of C coverage, the common pitfalls, the presentation by Manish and his pace were all remarkable. Gave a clear picture of the inner working of C language design.
— Shivanshu - Netapp

The course was well designed and coverage was satisfactorily deep. The linux programming assignments were designed to get a feel of real time issues and covered lot of areas of uncertainty. The project work suggested at the end of the course was invaluable.
— Somenath - EMC