Conditional Operator


The Conditional (? :) operator :-
Conditional operator is  a combination of "?" and ":" and takes three operands. It is useful for making two-way decisions.
General form of this operator is :-
 "conditional expression ? expression 1 : expression 2"
While executing this operator, conditional expression is evaluated first, if the result is non-zero, expression 1 is evaluated and is returned as the value of the conditional expression. Otherwise, expression 2 is evaluated and its value is returned as the value of conditional expression.
For example, consider an if else expression :-
if (x < 0)
    flag = 0;
else
     flag = 1;
But using conditional operator, it can be written as :-    
                                                           flag = (x < 0) ? 0 : 1;
Here if the value of x is smaller then 0, than the value of flag will be 0, and if the value of x is greater then 0, than value of flag will be 1.
When the conditional operator is used, the code becomes more concise and perhaps, more efficient. However, the readability is poor. It is better to use if statement when more than a single nesting of conditional operator is required.
  

Comments

Popular posts from this blog

Components of C language

Decision making using if statement

How to make payment for final certificate, migration, provisional for the students of last semester of ptu?