The Conditional Operators in C lang
Posted by
Ravi Kumar at Wednesday, August 31, 2011
Share this post:
|
The Conditional operator ? and : are sometimes
called ternary operators since they take three arguments.
Infact,they form a kind of foreshortened
IF-Then-ELSE.
Their general form is:
expression1?expression2:expression3
This expression: "if expression1 is TRUE
( that is, if its value is non-zero),
then the value returned will be expression2, otherwise the
value returned will be expression3".
Let us understand this with the help of a few
examples:
(a) Example:
int x,y;
scanf("%d",&x);
y=(x>5?3:4);
This statement will store 3 in y if x is greater
than 5, otherwise it will store 4 in y.
The equivalent If statement will be,
if(x>5)
y=3;
else
y=4;