By Stephen R. Davis

The unary operators in C++ are those operators that take a single argument. The unary mathematical operators are -, ++, and –. The minus operator changes the sign of its argument. A positive number becomes negative, and a negative number becomes positive:

int n = 10;
int m = -n;             // m is now -10

The ++ and the operators increment and decrement their arguments by one.

The increment and decrement operators are unique in that they come in two versions: a prefix and a postfix version.

The prefix version of increment is written ++n, while the postfix is written n++.

Both the prefix and postfix increment operators increment their argument by one. The difference is in the value returned. The prefix version returns the value after the increment operation, while the postfix returns the value before the increment. (The same is true of the decrement operator.) This is demonstrated in the following IncrementOperator program:

// IncrementOperator - demonstrate the increment operator
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int nNumberofArgs, char* pszArgs[])
{
    // demonstrate the increment operator
    int n;
    // first the prefix
    n = 1;
    cout << "The value of n is   " <<   n << endl;
    cout << "The value of ++n is " << ++n << endl;
    cout << "The value of n afterwards is " << n << endl;
    cout << endl;
    // now the postfix
    n = 1;
    cout << "The value of n is   " <<   n << endl;
    cout << "The value of n++ is " << n++ << endl;
    cout << "The value of n afterwards is " << n << endl;
    cout << endl;
    // wait until user is ready before terminating program
    // to allow the user to see the program results
    cout << "Press Enter to continue..." << endl;
    cin.ignore(10, 'n');
    cin.get();
    return 0;
}

The output from this program appears as follows:

The value of n is   1
The value of ++n is 2
The value of n afterwards is 2
The value of n is   1
The value of n++ is 1
The value of n afterwards is 2
Press Enter to continue . . .

This example demonstrates both the prefix and postfix increment. In both cases, the variable n is initialized to 1. Notice that the value of n after executing both ++n and n++ is 2. However, the value of ++n was 2 (the value after the increment), while the value of n++ was 1 (the value before the increment).