Conditional or Ternary Operator


Conditional or Ternary Operator


The conditional operator consists of 2 symbols the question mark (?) and the colon (:) 
The syntax for a ternary operator is as follows 

exp1 ? exp2 : exp3 

The ternary operator works as follows 

exp1 is evaluated first. If the expression is true then exp2 is evaluated & its value becomes the value of the expression. If exp1 is false, exp3 is evaluated and its value becomes the value of the expression. Note that only one of the expression is evaluated. 

For example 

a = 10; 
b = 15; 
x = (a > b) ? a : b 

Here x will be assigned to the value of b. The condition follows that the expression is false therefore b is assigned to x.

No comments:

Post a Comment