i'm puzzled with this statement

Hi friends,

Please tell me why the following statements are legal in C.
(At least, turbo c++ doesn't give an error!).

int x,y;

x = 2,3,4;
y = (2,3,4);

This evaluates to x=2 and y=4.
But why? Shouldn't it give a compilation error?
It is legal in many languages - the comma operator evaluates each of its arguments and returns the last. It's useful in some cases.
the statement
x = 2,3,4;
x gets 2;

It's effectively the same as x = 2;3;4; which doesn't do anything with 3 and 4.

x = (2,3,4);
x gets 4;

Try not to use comma's too often in normal statements. The only times I ever use them are:
1. Parameter lists int pow(int a, int b);
2. Multiple definitions int a, b, c;
3. for loops: for (int a = 1, b = 10; a < b; ++a, --b)

though some people frown upon usage #3 in this list as it makes things a little harder to read.
Last edited on
Ahh, I found a good reference on WHY:


The assignment operator = (15) has a higher precedence than , (17). So:
x = 2,3,4; is
"(x = 2) then 3 then 4"

x = (2,3,4);
"x = (2 then 3 then 4)"
"x = (4)
Last edited on
Topic archived. No new replies allowed.