+ 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?
4 odpowiedzi
+ 1
Because "cout" is after 2 increments
+ 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
+ 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
+ 4
After x++ is executed, the value of x is also incremented by 1. Why would it be 6?