0
int j = 3;
    for (int i = 0; i < 3; i++)
    {
        j=j++;
    }
    cout<<j<<endl;

My approach - Incase of post-increment value is assigned first to the variable then incremented so the following transitions should happen.

  1. i=0 j=3 (3 increments to 4)
  2. i=1 j=4 (4 increments to 5)
  3. i=2 j=5 (5 increments to 6)

Now the expected output should be 6 but it's 3, Why is my approach wrong? Thankyou

Retired Ninja
  • 4,785
  • 3
  • 25
  • 35
Eagle186f
  • 35
  • 4
  • `j=j++` assigns the pre-increment value to `j`, so `j` remains unchanged. You want just `j++`. – bereal Aug 05 '21 at 05:26
  • 1
    @bereal no, modifying a variable more than once between sequence points is undefined behavior. The value can be different in another environment. [Undefined behavior and sequence points](https://stackoverflow.com/q/4176328/995714) – phuclv Aug 05 '21 at 05:27
  • @phuciv you're right. – bereal Aug 05 '21 at 05:30
  • 1
    @phuclv Your duplicate is about C language, not C++. In modern C++ this is not undefined behavior. https://en.cppreference.com/w/cpp/language/eval_order – VLL Aug 05 '21 at 05:31
  • See also this answer in your link: https://stackoverflow.com/a/46171943/2527795 – VLL Aug 05 '21 at 05:33
  • @vll there are already modern C++ answer in the link I gave above. [C++17](https://stackoverflow.com/a/46171943/995714), [C++11](https://stackoverflow.com/a/4183735/995714) – phuclv Aug 05 '21 at 05:34
  • The `C#` duplicate seems out of place. – Retired Ninja Aug 05 '21 at 05:36

0 Answers0