How to Use the Autoincrement/Autodecrement Feature in C++

By Stephen R. Davis

C++ programmers very often use the autoincrement ++ or the autodecrement – – operators with loops that count something. Notice from the following snippet extracted from the WhileDemo example that the program decrements the loop count by using assignment and subtraction statements, like this:

// now loop that many times
while (nLoopCount > 0)
{
    nLoopCount = nLoopCount - 1;
    cout << "Only " << nLoopCount 
         << " loops to go" << endl;
}

A more compact version uses the autodecrement feature, which does what you may well imagine:

while (nLoopCount > 0)
{
    nLoopCount--;
    cout << "Only " << nLoopCount 
         << " loops to go" << endl;
}

The logic in this version is the same as in the original. The only difference is the way that nLoopCount is decremented.

Because the autodecrement both decrements its argument and returns its value, the decrement operation can be combined with the while loop. In particular, the following version is the smallest loop yet:

    while (nLoopCount-- > 0)
    {
        cout << "Only " << nLoopCount 
             << " loops to go" << endl;
    }

Believe it or not, nLoopcount– > 0 is the version that most C++ programmers would use. It’s not that C++ programmers like being cute (although they do). In fact, the more compact version (which embeds the autoincrement or autodecrement feature in the logical comparison) is easier to read, especially as you gain experience.

Both nLoopCount– and –nLoopCount expressions decrement nLoopCount. The former expression, however, returns the value of nLoopCount before being decremented; the latter expression does so after being decremented.

How often should the autodecrement version of WhileDemo execute when the user enters a loop count of 1? If you use the pre-decrement version, the value of –nLoopCount is 0, and the body of the loop is never entered. With the post-decrement version, the value of nLoopCount is 1, and control enters the loop.

Beware thinking that the version of the program with the autodecrement command executes faster than the simple “- 1” version (since it contains fewer statements). It probably executes exactly the same. Modern compilers are good at getting the number of machine-language instructions down to a minimum, no matter which of the decrement instructions shown here you actually use.