Some people have argued that ++i yields more efficient assembly code. When I checked, they were the same. In this situation, it doesn't matter.
in this specific case it really does not matter. When applied to primitives such
as int or char, they are indistinguishable in terms of efficiency. When applied
to objects of a user defined type the difference can be significant; the prefix
version avoids the creation of an anonymous temporary.
try this code:
int main()
{
struct A
{
A( int ii ) : i(ii) { cout << "A::constructor\n" ; }
A(const A& that ) : i(that.i) { cout << "A::copy_constructor\n" ; }
~A() { cout << "A::destructor\n" ; }
A& operator++() // prefix
{ ++i ; return *this ; }
A operator++(int) // postfix
{ A temp(*this); ++i ; return temp ; }
operator int() const { return i ; }
int i ;
};
cout << "------------- start -----------------------------\n" ;
A a1 = 100, a2 = 100 ;
cout << "a1: " << a1 << "\ta2: " << a2 << '\n' ;
cout << "------------- prefix++ ------------------------\n" ;
int i = ++a1 ;
cout << "a1: " << a1 << "\ti: " << i << '\n' ;
cout << "------------- postfix++ -----------------------\n" ;
i = a2++ ;
cout << "a2: " << a2 << "\ti: " << i << '\n' ;
cout << "------------- done -----------------------------\n" ;
};
and here is the output:
------------- start -----------------------------
A::constructor
A::constructor
a1: 100 a2: 100
------------- prefix++ ------------------------
a1: 101 i: 101
------------- postfix++ -----------------------
A::copy_constructor
A::destructor
a2: 101 i: 100
------------- done -----------------------------
A::destructor
A::destructor
we can really see the difference now between ++a1 and a2++, both
in terms of the difference in semantics as well as performance.
if you are into a lot of C++ programming, it is a good idea to get
into the habit of using the prefix versions of ++ and -- as the normal
case. even for builtin types like int, the prefix version is as efficient
as the postfix version.