-1

This program is stuck in an infinite loop when i++ is used but gives right output when ++i is used. Why does this happen if we use post-increment rather than pre-increment.

#include <iostream>

int main (){
    int i = 0;
    while (i < 5)
    {
        std::cout << i;
        i = i++;
    }
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302

1 Answers1

1

Ignoring the loop, consider

int i = 0;
i = i++;

Calling the post-increment returns the current value then increments the variable i. This means the left hand side, i, will be set to the current value, 0. So, i remains at zero and your loop never ends.

Instead, using

int i = 0;
i = ++i;

calls the pre-increment, so the incremented value is returned, and i therefore gets set to 1.

If you don't use i = and just put

int i = 0;
++i;

or

int i = 0;
i++;

i will be equal to 1 after each increment.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
  • Post-increment can increment at the end of the statement; it doesn't have to increment immediately. So the result, at this level of analysis, could be 0 or 1. But, regardless, `i = i++` attempts to modify `i` twice without an intervening sequence point. Because of that, the behavior of the program is undefined. Sure, you can postulate various reasonable operation sequences for this particular expression, but the general rule applies in much more general situations which you (and the compiler) cannot analyze, which is why the behavior is undefined. (C++20 might have messed with this) – Pete Becker Aug 17 '23 at 15:32
  • Fair @PeteBecker - I tried to give a high level answer but you are quite right. – doctorlove Aug 17 '23 at 16:30