Increment and Loop | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

10th Dec 2017, 9:00 AM
Trường Giang
Trường Giang - avatar
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
10th Dec 2017, 9:11 AM
Tamra
Tamra - avatar