0

In C, is

a[i] = a[++i];

equivalent to

a[i] = a[i+1]; i++;

That is, which side of the assignment is evaluated first and what value of i is used on the left side? Or is this assignment ambiguous?

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
push2eject
  • 203
  • 2
  • 6
  • 8
    Undefined behaviour. Don't write such code. – Amadan Jun 11 '15 at 04:47
  • @Amadan, actually, it is not. From http://stackoverflow.com/a/3914332/434551, "C++03 [Section 5/4] says Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. " Here, `i` is being modified only once. – R Sahu Jun 11 '15 at 04:52
  • @RSahu: See [this answer](http://stackoverflow.com/a/2989841/240443), a quote from K&R, with this exact example. The fact that it does not violate one constraint does not mean it can't violate another. – Amadan Jun 11 '15 at 04:53
  • 4
    It is a duplicate of [this question](http://stackoverflow.com/q/949433/1009479), [the second answer](http://stackoverflow.com/a/4177063/1009479) explained it explicitly. – Yu Hao Jun 11 '15 at 05:04
  • 1
    @RSahu http://ideone.com/bzC8EQ – BLUEPIXY Jun 11 '15 at 05:15
  • @BLUEPIXY, I stand corrected :) – R Sahu Jun 11 '15 at 05:16
  • @Yu Hao: Thank you, that Q&A clearly resolves my question. The behaviour is undefined. – push2eject Jun 11 '15 at 05:20

1 Answers1

3

In the same sequence point you are using and incrementing i

a[i] = a[i++];

which will lead to undefined behavior.

a[i] = a[i+1];
i++;

is good.

And to answer your question are they same ? No they are not !! One if well defined and another is not.

Check this answer

Community
  • 1
  • 1
Gopi
  • 19,784
  • 4
  • 24
  • 36