Mateen Ulhaq
Mateen Ulhaq

Reputation: 27201

Is `y = x = x + 1;` undefined behavior?

Is this code:

y = x = x + 1;

undefined behavior in C?

Upvotes: 18

Views: 1174

Answers (3)

user142019
user142019

Reputation:

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);

Upvotes: 33

Chris Lutz
Chris Lutz

Reputation: 75399

No. You only modify x once, and due to the right-associativity of = that assignment happens before the assignment to y. Even if it did happen after, there's still only one modification of x. Your statement is as legal as y = ++x.

Upvotes: 9

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84169

No, your expression is properly defined. You probably were looking for y = x = x++;, which is not.

Upvotes: 17

Related Questions