Conditional Expression C

If we write a simple program of finding maximum of two numbers, using if-else, we can write

The above program can be replaced by a conditional expression (a > b)? a: b; . The general form of a conditional expression is

Expression1? Expression2: Expression3;

Here Expression1 is evaluated first. If it is true then Expression2 is evaluated and that is the value of the expression. If it is false, Expression3 is evaluated and gives value of conditional expression. Thus in our example, if a is greater than b then value of expression is a, else value of expression is b. Conditional expressions can appear on right hand side of a simple assignment. The resulting value is assigned to the variable on the left.
E.g.

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

Apart from arithmetic statements, conditional operators can be used in other places as well.
E.g.

(j = = 1 ? printf(“Anyone”): printf(“No one”) );

Conditional operators can be nested

E.g.

If operands (i.e. Expression2 and Expression3) differ in type, then the resulting data type of conditional expression will be determined by conversion rules stated in previous chapter.
E.g.

(n >0) ? f : n;

If f is a float and n is an integer then the result is of type float. The limitation of conditional operators is that only one statement can appear after ‘?’ or after ‘.’.

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

C Topics