Condtional operator ? :


1.   The conditional operator ? :

Although this is not one of the commands which control the program flow, conditional operator is similar in structure to the if-else block. Syntax of this operator is given below.
condition ? expression1 : expression2 ;
If the expression Condition gives a logical truth then the program will calculate the expression1 and fi the expression Condition is logical untruth than the program will calculate the expression2.
For example:
x = (x > 1) ? –x : x;
If variable x is greater than 1, the program will calculate the first expression and the variable x on the left side of the equal sign gets the negative value because the variable x changes its sign.  If the x is smaller than 1 that means that the program calculates the second expression and in this case the variable x doesn’t change.
The expression in condition as a result must return logical type. Alternative expressions after question mark must return the result which is of the same type or they must be able to reduce the same type with built in conversion rules.
IMPROTANT – The conditional operator are used for simple tests when the command fit into one line. In other case the code becomes vast.
We can write the discriminant example which is covered in previous post using the conditional operator. For more information please visit the:
Here is how the discriminant example would look like using the conditional operator.
((discriminant = b * b -4 * a * c) >= 0) ?
 (x1 = (-b + discriminant /2 /a, x2 = (-b + discriminant) / 2 / a) :
(cout << “The root isn’t correct.”, x1 = x2 = 0)
Share on Google Plus