Confusion with this calculation.

I'm fairly new to this and have been going through the tutorial. However I've come across something that genuinely confuses me:

1
2
3
4
5
6
7
  a = (b = 10, b+= 10, b++); // Results as 20..
    cout << endl << a;
    cout << endl << b;  // Results as 21.

       
    a = (b = 10, b+= 10, ++b); // Results as 21.
    cout << endl << a;


I don't understand why it would ignore the last increment of 'b' in the first assignment of 'a' just because the increment is written as a suffix, even though 'b' evaluates to be 21 afterwards, and why it's considered in the assignment of 'a' when written as a prefix.

I understand that there is a difference how the computer calculates the increment based off of if it's a suffix or prefix, but I don't see why it completely ignores it when assigning the value to 'a'.

This may not be that significant, but it's something I'd like to understand if someone would bother explaining it.
Last edited on
Sigh719 wrote:
I don't understand why it would ignore the last increment of 'b' in the first assignment of 'a' just because the increment is written as a suffix, even though 'b' evaluates to be 21 afterwards, and why it's considered in the assignment of 'a' when written as a prefix.


Post increment makes a copy, increments the original, and returns the copy.
Pre increment increments the original and returns the original.

1
2
3
4
5
6
7
8
int a = 1, b = 1;
std::cout << a   << std::endl;
std::cout << a++ << std::endl; //post increment
std::cout << a   << std::endl;
std::cout <<     << std::endl;
std::cout <<   b << std::endl;
std::cout << ++b << std::endl; //pre increment
std::cout <<   b << std::endl;

1
1
2

1
2
2
Last edited on
Thanks for the reply. I guess I figured out that concept but thanks for reassuring it. Out of curiosity, if you know, why are there two ways to increment? What utilization does a++ provide that ++a doesn't? Why shouldn't I use ++a every time I need to increment?
You should use pre-increment (++a) everywhere where post-increment isn't explicitly needed. (because post-increment makes a copy of the object, it uses more resources and is generally slower.)

Post-increment is useful for incrementing a value that you need to use before it actually increments.
A good example is the copy algorithm. You could re-implement it as follows:
1
2
3
4
5
6
7
template<class InputIter, class OutputIter>
OutputIter MyCopy(InputIter first, InputIter last, OutputIter dest)
{
    while(first != last)
        *dest++ = *first++ //sets the value of *dest to the value of *first, THEN increments dest and first.
    return dest;
}
Last edited on
It's mostly a syntactic shortcut, if anything. You can always do the same thing it does the long way if you want, and it's historic to C.
Topic archived. No new replies allowed.