MCS-011 Problem Solving and Programming

First year, Semester 1

Chapters

Newsletter

Comma and Conditional Operators

C provides an called as the conditional operator (?:) which is closely related to the if/else structure. The conditional operator is C’s only ternary operator - it takes three operands. The operands together with the conditional operator form a conditional expression. The first operand is a condition, the second operand represents the value of the entire conditional expression it is the condition is true and the third operand is the value for the entire conditional expression if the condition is false.

The syntax is as follows:

(condition)? (expression1): (expression2);

If condition is true, expression1 is evaluated else expression2 is evaluated. Expression1/Expression2 can also be further conditional expression i.e. the case of nested if statement

For eg. 

 x= (y<20) ? 9: 10;
 This means, if (y<20), then x=9 else x=10


Comma Operator 

A comma operator is used to separate a pair of expressions. A pair of expressions separated by a comma is evaluated left to right, and the type and value of the result are the value of the type and value of the right operand. All side effects from the evaluation of the left operand are completed before beginning evaluation of the right operand. The left side of comma operator is always evaluated to void. This means that the expression on the right hand side becomes the value of the total comma-separated expression. For example,

x = (y=2, y - 1);

first assigns y the value 2 and then x the value 1. Parenthesis is necessary since comma operator has lower precedence than assignment operator.  
 

Report an issue

Reporting: Comma and Conditional Operators (topic)

Related Posts