Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why post-increment needs to make a copy while pre-increment does not

I know this issue has been discussed several times , but I could not find a post which explains why a copy needs to be made in case of a post-increment operation.

Quoting from a stackoverflow reply:

int j = i++; // j will contain i, i will be incremented.
int j = ++i; // i will be incremented, and j will contain i+1.

Which perfectly makes sense when the definition of post/pre increment is considered. Many times when comparing the performance of pre/post increment it is said that post increment needs to make a copy, increment it and return the copy while pre-increment just increases value and does not create a copy.

Although performance has been compared in tens of posts, I really could not find any explanation on why a copy has to be made in the case of post-increment. Why doesn't it return the old value and then increments the value of the variable by one(or however way operator is overloaded), rather than creating a new object and return that one.

like image 688
ralzaul Avatar asked Jun 19 '15 15:06

ralzaul


People also ask

What is the difference between post increment and pre increment?

In Pre-Increment, the operator sign (++) comes before the variable. It increments the value of a variable before assigning it to another variable. In Post-Increment, the operator sign (++) comes after the variable. It assigns the value of a variable to another variable and then increments its value.

Why pre increment is better than post increment?

Pre-increment is faster than post-increment because post increment keeps a copy of previous (existing) value and adds 1 in the existing value while pre-increment is simply adds 1 without keeping the existing value.

Which has more precedence post increment or pre increment?

The precedence of post increment is more than precedence of pre increment, and their associativity is also different. The associativity of pre increment is right to left, of post increment is left to right.

What is difference between post increment and pre increment in for loop?

Pre-increment ++i increments the value of i and evaluates to the new incremented value. Post-increment i++ increments the value of i and evaluates to the original non-incremented value.


1 Answers

The difference is someval++ returns what someval is before the increment and to do that you need remember what someval is with a copy. How else would you return the original value while updating it if the original value wasn't stored somewhere?

like image 100
NathanOliver Avatar answered Nov 15 '22 20:11

NathanOliver