Pre and post increment

I know a built in type is not an object but I really want to understand how post and pre increment works. So is the explanation below correct?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include<iostream>
using namespace std;

int main(){
  int x, y ;
  x = y = 1;
  int z;
  /*The ++ POST_INCREMENT operator
  * This is how it is actually called
  * z.operator=(x.operator++())
  * Now, x calls operator++() so, it is passed as default as an argument.
  * The operator++() now does the following
      1* It makes a DEEP copy of x
      2* It then increments x by 1
      3* Returns the copy it made in step 1
  * So, if we print z we get 1 and if we print x we get 2

  */
  z = x++;
  cout << z <<endl;
  cout << x <<endl;


  /*The ++ PRE_INCREMENT operator
  * This is how it is actually called
  * z.operator=(operator++(y))
  * The operator++(y) now does the following
      1* It then increments y by 1
      3* Returns y
  * So, if we print z we get 2 and if we print y we get 2

  */
  z = ++y;
  cout << z <<endl;
  cout << y <<endl;



}
not sure what you are saying on the copy. It does not copy anything (in this example!).


z = x++; // this is the same as z = x; x++; It does the assignment first, the increment last.

z = ++y; // increment first, assign last.

No copy that I know of is made, apart from your code copying into z.
I would think that modern compilers can avoid any copying at least most of the time, and if they do copy, I would think it would be at the register level. There are places (and object types) where the copy is needed, which is why its faster to do it pre in some cases.
Last edited on
Actually thinking as if they are objects isn't the copy necessary? Because there is a return at the end which is the same value of the argument but inside the increment occurs. Maybe I am over thinking.
since the type of x is int, there is no function call: a built-in operator is executed.

For built-in operators, x++ and ++x both cause a write to x to be performed at some point between the previous and the next semicolon (roughly), and also x++ returns the original value, ++x returns the original value plus one.

For class and enum types, yes, a function call is made to operator++(x) or x.operator++() (whichever is a better match) for preincrement or to operator++(x, 0) or x.operator++(0) (whichever is a better match) for post-increment. What those functions do is up to them.
Topic archived. No new replies allowed.