+ 1
Increment and Loop
I have some code in Lesson: Loop âââ #include <iostream> using namespace std; int main() { int num = 1; while (num < 6) { cout << "Number: " << num << endl; num = num + 1; } return 0; } âââ When i replace num = num + 1 by num = ++ num My code will run exactly. But when i replace it by num = num++, my code will run with infinity loops. Output is: Number 1 Two increment operator: prefix and postfix will increase value of num but why I receive two output and they arenât the same?
1 Answer
+ 14
++num and num++ behave slightly differently.
++num increments before most other operations occur.
num++ increments late in the order of operations. The = assignment actually works *before* the increment, in this case. So "num = num++;" assigns the old value of num to itself, and then it increments. The new value is then discarded, because the assignment already happened.
To get this to work, you can just shorten it to "num++;" or "++num;" to increment.
Also see:
https://www.sololearn.com/Discuss/212490/?ref=app