Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Jun 2, 2000



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Prefer Prefix Operators to Postfix Ones for Non-Fundamental Types

Postfix operators, namely ++ and --, are less efficient than their prefix counterparts because the compiler usually creates a temporary copy of the object before applying the operator to an object. When using fundamental types such as int or char, most compilers can optimize the code and eliminate the performance overhead associated with postfix operators. Therefore, there's no real difference between the the following expressions:

 for (int j=0; j<n; j++) // postfix
 for (int j=0; j<n; ++j) // prefix

However, if we use a user-defined type instead of a fundamental type, most compilers won't be able to optimize the postfix version. In the following example,

 string s = "hello";
 string::iterator si;
 for (si= s.begin(); si<s.end(); si++) // postfix
 for (si= s.begin(); si<s.end(); ++si) // prefix

Chances are high that the prefix version of the for-loop is more efficient than its postfix counterpart because si is an iterator, not a fundamental type. For this reason, always use prefix operators unless you truly need to use the postfix version.

Danny Kalev
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date