0

Consider the following code:

#include <iostream>

int main()
{
    int i = 1; 
    i = (i = i + 1) + 1;
    int j = 1;
    j = j++ + 1;
    std::cout << i << std::endl;  //3
    std::cout << j << std::endl;  //2
}

What's the difference?

user3663882
  • 6,957
  • 10
  • 51
  • 92
  • 8
    There is no significant difference--both modify an operand twice between sequence points, so both give undefined behavior (since C++11, the standard no longer uses the phrase "sequence point", but the same basic idea still applies). – Jerry Coffin May 25 '15 at 19:05
  • See [here](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) –  May 25 '15 at 19:05
  • See [Undefined behavior and sequence points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – Jeff Ames May 25 '15 at 19:05
  • @Jerry It seems to me that the latter is still UB, but the former shouldn't be since C++11 (it's equivalent to `i = ++i + 1`, not to `i = i++ + 1`) – Andy Prowl May 25 '15 at 19:24
  • @JerryCoffin `i = (i = i + 1) + 1;` is **not** UB in C++11 – M.M May 25 '15 at 21:39
  • @MattMcNabb Why? In c++ 14 is UB? – user3663882 May 25 '15 at 21:43
  • @user3663882 no it's not UB in C++14 either. See example 5 near the end of [this answer](http://stackoverflow.com/a/4183735/1505939) – M.M May 25 '15 at 21:44
  • @MattMcNabb Not clear i = i + 1 causes side effect, therefore it should be UB. – user3663882 May 25 '15 at 21:53
  • @user3663882 no it isn't UB, it is explained in the answer I linked. Since C++11 the side-effect is sequenced before the outer assignment. – M.M May 25 '15 at 21:56

0 Answers0