+ 1

Can't wrap my head around Increment and Decrement operation

I have the following code #include <iostream> using namespace std; int main() { int x = 5; int y = 6; x++; ++x; y++; ++y; cout << x << endl; cout << x << endl; cout << y << endl; cout << y << endl; return 0; } If I compile and run I get this 7 7 8 8 why am I getting 7 instead of 6 after x++ gets executed?

3rd Sep 2018, 11:41 AM
Alokananda Y
Alokananda Y - avatar
4 Respostas
+ 1
Because "cout" is after 2 increments
3rd Sep 2018, 1:20 PM
Emerson Prado
Emerson Prado - avatar
+ 6
x++ is postfix increment operator, as Anna told x++ will first use its value then it will increment it. int x = 5; cout << x++ << endl ; cout << x << endl ; Output : 5 //First used(print) its value 6 //Then incremented on next statement
3rd Sep 2018, 7:55 PM
blACk sh4d0w
blACk sh4d0w - avatar
+ 5
x++ means that x is incremented immediately. It's the same as x += 1 or x = x + 1. If used in an assignment like y = x++, x will be assigned to y first and then incremented. y = ++x means that x is incremented before it is assigned to y. If you don't use it in an assignment, x++ is pretty much the same as ++x. Note that you only cout x after it was incremented twice. So it's 5+2
3rd Sep 2018, 11:47 AM
Anna
Anna - avatar
+ 4
After x++ is executed, the value of x is also incremented by 1. Why would it be 6?
3rd Sep 2018, 11:45 AM
Hatsy Rei
Hatsy Rei - avatar