Hello, I'm struggling a bit to understand what the difference is, say, between ++n and n++. These were some examples I was given, could someone break them down a bit more for me, mathematically? Thank you.
Examples:
int x = 10, result;
result = x++; // result = 10 and x = 11
result = ++x; // result = 12 and x = 12
result = --x; // result = 11 and x = 11
result = x--; // result = 11 and x = 10
I thought the examples might be incorrect, so I made a program quickly to check. In your example, the integer x was not set to 10 before each calculation which caused me to be confused.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main(){
int x = 10, result;
result = x++;
cout << "result = " << result << " and x = " << x <<endl;
x = 10;
result = ++x;
cout << "result = " << result << " and x = " << x <<endl;
x = 10;
result = x--;
cout << "result = " << result << " and x = " << x <<endl;
x = 10;
result = --x;
cout << "result = " << result << " and x = " << x <<endl;
return 0;
}
here's the output:
result = 10 and x = 11
result = 11 and x = 11
result = 10 and x = 9
result = 9 and x = 9
Here's an explanation that hopefully makes sense:
result = x++ is like 2 expressions:
result = x and x = x+1
Yeah but wouldn't it have to run twice in order to get that number? x++ should only be x = x+1, not +1 +1
EDIT: I think I understand what you meant, but I was not considering the examples as one block. I was thinking of them each individually, with x returning to the initial '10' each time.
Actually you should be thinking it in terms of a mathematical expression. We all learned in elementary school the order of operations and whatnot. Well, the computer has that as well, as evident in @PBachmann's example.
Notice how there is the result = x++; vs result = ++x;.
In the first part, the compiler sees an Lvalue, and goes "Oh, ok. So we're assigning a value to 'result'". Then it goes forward (meaning left to right) and sees an "=". Then what happens is it sees a valid Rvalue (aka the x) and goes "Oh goody, the stack is complete and valid. Now I can return 'result' just like the user wanted."
Versus
The other side, after the first part runs, the compiler goes "Wtf is this? 'result = ++'" ????
So then it doesn't resolve anything until the highest order of operators is resolved first because the "result" wasn't able to be assigned to anything,