0
Infinite Loop
Why when changing x++; to x=x++; cause an infinite loop? while (x<=20) { cout<<x<<endl; x=x++; }
1 Odpowiedź
+ 4
It's not strange at all, since the value of x remains 0. If you understand how post increment works, it becomes very easy to see why. The behaviour of x++ is to increase x by 1 and return the old value of x. The steps involved in x=x++ are:
1. the right hand side (x++) returns x
2. increments x by 1
3. assigns x to old value of x, returned in step 1
hence x does not change.
x=x++ is equivalent to
int oldValue = x;
x++;
x=oldValue;
to get your intended you should just use x++ or ++x or x=++x (the last code redunant though)