C – Is y = x = x + 1 Undefined Behavior?

c++undefined-behavior

Is this code:

y = x = x + 1;

undefined behavior in C?

Best Answer

Answer to your question
No.

What will happen
This will happen:

int x = 1; /* ASSUME THIS IS SO */
y = x = x + 1;

/* Results: */
y == 2;
x == 2;

How it compiles
The same as:

x += 1;
y = x;

Why this is not undefined
Because you are not writing x in the same expression you read it. You just set it to itself + 1, then assign y to the value of x.

Your future
If you find the code confusing you can use parentheses for readability:

y = x = (x + 1);
Related Question