Wednesday, January 9, 2008

The Comma Operator

Can U predict output of this program:

void main()
{
int p=3,q=5,x,y;

x = p,q;
y = (p,q);
printf ("%d %d",x,y);
}

a. 3 5
b. 5 5
c. 3 3
d. 5 3
e. None (may be error)



The ans is a. 3 5

The comma separates the elements of a function argument list. The comma is also used as an operator in comma expressions. Mixing the two uses of comma is legal, but you must use parentheses to distinguish them. the left operand E1 is evaluated as a void expression, then E2 is evaluated to give the result and type of the comma expression. By recursion, the expression

E1, E2, ..., En

results in the left-to-right evaluation of each Ei, with the value and type of En giving the result of the whole expression.

No comments: