? and : are called conditional operator. It is also called ternary operator as it takes three operands.
We have 2 syntax for these operator.
- z= (condition) ? ( expression 1) : ( expression 2);
- (condition) ? z = expression 1 : (x = expression 2);
z is the variable which will hold the result after condition and expressions evaluated.
*In the absence of parenthesis in syntax 2 ,error will be reported.*
Example
a>b ? g=a : g=b ; incorrect syntax
a>b ? g=a : (g=b) ; correct syntax
Example
x = (y< 20) ? 9: 10;
This means if y is less than 20 then x=9 else x=10.
- It is not necessary that the conditional operator should be used only in arithmetic statements.
Example
int i;
scanf(”%d”,&i);
(i== 1? printf(”hello): printf(”hi”));
- The conditional operator can be nested.
Example
z = (a>b ? (a>c ? 3: 4): ( b>c ? 6 : 8));




Recent Comments