The ? Operator - C Operator

C examples for Operator:Conditional Operator

Introduction

The ternary operator ? takes the general form

Exp1 ? Exp2: Exp3 ;

where Exp1 , Exp2 , and Exp3 are expressions. Notice the use and placement of the colon.

C ternary operator ? replaces certain statements of the if-then -else form.

The ? operator works like this: Exp1 is evaluated. If it is true, Exp2 is evaluated and becomes the value of the expression.

If Exp1 is false, Exp3 is evaluated, and its value becomes the value of the expression.

For example, in

 
x = 10;
y = x>9 ? 100 : 200;

y is assigned the value 100. If x had been less than 9, y would have received the value 200.

The same code written using the if-else statement is

x = 10;

if( x > 9 ) 
   y = 100;
else 
   y = 200;

Related Tutorials