Discussion





Discussion

An ancient joke about C++ was that the language is called C++ and not ++C because the language is improved (incremented), but many people still use it as C (the previous value). Fortunately, the joke is now obsolete, but it's a helpful illustration for understanding the difference between the two operator forms.

For ++ and --, the postfix forms return the original value, whereas the prefix forms return the new value. Prefer to implement the postfix form in terms of the prefix form. The canonical form is:

T& T::operator++() {        T& T::operator--() {     // the prefix form:
 // perform increment        // perform decrement    //   - do the work
 return *this;               return *this;           //   - always return *this;
}                           }

T T::operator++(int) {      T T::operator--(int) {   // the postfix form:
 T old( *this );             T old( *this );         //   - remember old value
 ++*this;                    --*this;     //   - call the prefix version
 return old;                 return old;             //   - return the old value
}                           }

In calling code, prefer using the prefix form unless you actually need the original value returned by the postfix version. The prefix form is semantically equivalent, just as much typing, and often slightly more efficient by creating one less object. This is not premature optimization; it is avoiding premature pessimization (see Item 9).


     Python   SQL   Java   php   Perl 
     game development   web development   internet   *nix   graphics   hardware 
     telecommunications   C++ 
     Flash   Active Directory   Windows