### Understanding operators?

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
See section Increment and Decrement in http://en.cppreference.com/w/cpp/language/operators
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.
 ``1234567891011121314151617`` ``````int main(){ int x = 10, result; result = x++; cout << "result = " << result << " and x = " << x <

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

whereas result = ++x is:
result = x+1 and x = x+1
Last edited on
Thank you, I was thinking too that they may be incorrect? The 12 didn't seem to make any sense. It's a lot more clear now.
 Thank you, I was thinking too that they may be incorrect? The 12 didn't seem to make any sense.

What do you mean? 10+1+1 is 12.
Basically ++x returns the value x+1 to any variable, while x++ returns x+1 to the variable itself (here, x)
Last edited on
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.
Last edited on
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,

http://en.cppreference.com/w/cpp/language/operator_precedence
Topic archived. No new replies allowed.