0

What is the difference between i++ and ++i?

4th Oct 2016, 7:29 AM
crisscrossApplesauce
crisscrossApplesauce - avatar
2 Antwoorden
+ 8
Simplified answer for you. ++x Adds 1 to x's value and then assigns it. x++ Assigns x's value then adds to x. int x = 3; int y = 5; cout << y; This outputs y's value of 5. Now using the increments. int x = 3; int y = 5; y = ++x; y's previous value is now cleared, and ++x modifies x's value to x+1, then assigns it to y. cout << y; It now outputs 4. (x = 4, y = 4) If it had been y = x++, x's value would have been assigned to y, then x's value would be x+1. It would output 3. (x = 4, y = 3)
7th Oct 2016, 2:47 PM
Chese780 ~
Chese780 ~ - avatar
+ 1
The increment in i will be the same, the difference is in the return value of the statement. Every statement has a return value, and the ; at the end of every sentence is used to tell the compiler to discard it. ++i gives the value of i AFTER adding 1 and i++ gives the FORMER value of i. (¿Or it was the other way around?, I can't recall). The difference is only noted if you are using this return value for something. Try int a = i++; or int a = ++i; In both cases i is incremented by 1, but a would hold a different value.
6th Oct 2016, 8:56 PM
Juan Pablo Giuttari
Juan Pablo Giuttari - avatar