# x = (y = 3, y + 1) why 3 is assigned to y first before calculating y + 1

This is a discussion on x = (y = 3, y + 1) why 3 is assigned to y first before calculating y + 1 within the C Programming forums, part of the General Programming Boards category; Consider this simple program: Code: main() { int x, y; x = (y = 3, y + 1); printf("x = ...

1. ## x = (y = 3, y + 1) why 3 is assigned to y first before calculating y + 1

Consider this simple program:

Code:
```main()
{
int x, y;
x = (y = 3, y + 1);
printf("x = %d and y = %d", x, y);
}```
It shows the output "x = 4 and y = 3";

I just want to know why it first of all assigns the value 3 to y instead of calculating y + 1 as "+" has a higher priority as compared to "=".

Thanks a lot.

2. I might be wrong, but from what I understand the comma is a sequence point, so y = 3 is evaluated before y + 1.

3. It's because the comma operator "associates left to right", so the left part is performed before the right part. See:
http://www.cppreference.com/operator_precedence.html

[Since the comma operator is at the bottom of the precedence list, you may have to scroll down to find it].

So, the left half is evaluated first (y = 3), then the right half (y + 1). And the final result is assigned to the x variable.

Of course, if you did the "y + 1" first, it would have a undefined value.

Edit: Fix up so that my reply applies to both the original post and Laserligth's answer.

--
Mats

4. Originally Posted by hitesh_best
I just want to know why it first of all assigns the value 3 to y instead of calculating y + 1 as "+" has a higher priority as compared to "=".
But comma itself has a priority much lower than either of those operators, so it splits the expression into self-contained portions. Because comma is also a sequence point, the compiler evaluates the left portion first.