18

Is this code:

y = x = x + 1;

undefined behavior in C?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
Mateen Ulhaq
  • 24,552
  • 19
  • 101
  • 135

3 Answers3

32

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);
  • 2
    Just for your info, muntoo, as the "return value" of assignment is it's own value, you can also use it for other things, like `if ( 1 == x = 1 )`, which is a pretty common bug and the reason, developers prefer to write `1 == x` instead of `x == 1` (because you can't assign x to 1). – anroesti Feb 05 '11 at 23:02
  • 34
    The only developers I know who write things like `1 == x` are ones I would not work with... – R.. GitHub STOP HELPING ICE Feb 05 '11 at 23:21
  • 19
    @andre: No, "developers" don't prefer to write that. It's gross, unclean, and useless; just join the last decade and turn on your compiler warnings. – GManNickG Feb 05 '11 at 23:43
17

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

Nikolai Fetissov
  • 82,306
  • 11
  • 110
  • 171
9

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.

Michael Mrozek
  • 169,610
  • 28
  • 168
  • 175
Chris Lutz
  • 73,191
  • 16
  • 130
  • 183