Increment and decrement operator help

I've been slowly getting my way through a teach yourself C++ book and so far its been great. I like the structure and explanations and feel I am learning something! But I've hit a hurdle in a place I least expected it and could do with an expansion of the explanation.

I'll just copy the examples from the book...

Assuming count starts as 5 in all examples,

 
  total = ++count + 6;   
So this is "total = count + 1 + 6 = 12". I get this.

 
  total = --count + 6;   
... this is "total = count - 1 + 6 = 10". I get this too.

But it's the postfix operators that have me stumped.

 
  total = count++ + 6;   
(later re-written as 6 + count++)

Apparently this is 11. I just don't get it! Not unless it reads as "total = 6 + count = 11", then count is changed to 6 without affecting total.

Same for
 
total = 6 + count--;


Apparently this is also 11. Same thing, I can only see it if it reads as "total = 6 + count = 11", then count is changed to 4 without affecting total.

Any help would be great. I don't really want to skip passed this chapter section.

Thank you
Last edited on
Thats how this operator works, in your example:
total = count++ + 6
total = 5 + 6 = 11 than you increment count.
it works the same as:
total = count + 6; count += 1;

The difference between ++count and count++ is that ++count adds 1 to count variable before calculating whole expression but count++ adds 1 after it. I hope it makes sense.
Last edited on
ahhh, OK thank you. It does make sense now. The use of ++ or -- is after everything else.

Thank you for the help.
no, whether it is before or after other operations depends on whether it is on the front or back of the variable and from there follows standard c++ order of operations rules. As a unary operator, it is pretty much at the top of the order of operations (after () and groupings).

x = 0; y = 0;
x = y++; //x = 0, y becomes 1 after assignment.
x = ++y; //x = 1, y is one before assignment.
Last edited on
Thanks Jonnin, I was a bit careless with my response. The sequence of calculation had been explained to me in the book and on the table of operators it is indeed very close the top of list.
Topic archived. No new replies allowed.