Reputation: 1886
In C++ I understand that (++i)
should return a reference to i
because the need of concatenation of operators, but what I can't figure out is:
Why (i++)
should return i
by value?
Can anyone please clarify.
Upvotes: 10
Views: 1522
Reputation: 195
5 cents:
As a consequence of i++
making a copy, it is slower for non-POD variables (i.e. iterators). You should use ++i
anywhere when possible.
I personaly always use for(...;...;++i)
instead of for(...;...;i++)
, although compiller should optimize that.
Upvotes: 0
Reputation: 719
While prefix ++i
returns the incremented value and the suffix i++
returns the old value and increments it afterwards the operator selection is significant if you care for the CPU cycles. Prefix increment is faster ;-)
Upvotes: 0
Reputation: 12465
i++ This returns the value of the i before it is incremented. So the idea is that if you want to use i in a function, and then increment the value after using it, you can do that in one step. As an example, here is how I would overload that operator for integers.
Integer Integer::operator++()
{
Integer returnValue = *this;
this->increment();
return returnValue;
}
So it increments the value and then returns what it used to be. It also doesn't return a reference, because returning a reference would be different from what was originally passed, which would break cascading.
++i This increments the value of i, and then returns the new value. So you could use this in a situation where you want to increment i and then use the new value in your function.
Integer Integer::operator++(Integer i)
{
i.increment();
return i;
}
So the value it returns is the incremented value of i.
Upvotes: 2
Reputation: 2088
int i = 0;
Console.Writeline(i++); // Output 0, after that, i will be 1
int x = 0;
Console.Writeline(++x); // Output 1
Note: code is in C#
Upvotes: 1
Reputation: 146988
If you're ever in a scenario where it matters, you're doing it wrong.
Upvotes: -4
Reputation: 19938
Let foo
be some function. foo(i++)
calls foo(i)
with the old value of i
and increments i
, hence the need to build a temporary copy. foo(++i)
increments i
and then calls foo
with the incremented value, so for better performance we can reuse the same variable, no need to have a temporary copy.
Upvotes: 4
Reputation: 523574
++i
can be written as
prefix_inc (this) {
increase this by 1
return this
}
Since the real i
is returned, we can take reference of it. However, i++
looks like
postfix_inc (this) {
set old_this = copy of this
increase this by 1
return old_this
}
as old_this
is just a local variable, the reference of it is pointless after i++
is completed. So logically it should return an rvalue.
Upvotes: 19
Reputation: 49226
i++
returns a value because it is returns the old value of i
, while i
is increased by 1
.
A basic implementation of this would be:
int i++() {
int old = i;
i = i + 1;
return old;
}
So, if it returned a reference, it would be the wrong value... since i
's value has been incremented!
Upvotes: 27