Perform Unary Operations in C++ - dummies

Perform Unary Operations in C++

By Stephen R. Davis

C++ offers all the common arithmetic operations: C++ programs can multiply, add, divide, and so forth. Programs have to be able to perform these operations to get anything done. Arithmetic binary operators — those operators that take two arguments — are familiar to most people from school days. But consider the unary operators, which take a single argument (for example, –a). Many unary operations are not so well known.

The unary mathematical operators are plus, minus, plus-plus, and minus-minus (respectively, +, –, ++, and – –). The minus operator changes the sign of its argument. Positive numbers become negative and vice versa. The plus operator does not change the sign of its argument. The plus operator is rarely, if ever, used.

int var1 = 10;
int var2 = -var1;  // var2 is now -10

The latter expression uses the minus unary operator () to calculate the value negative 10.

The ++ and the – – operators might be new to you. These operators (respectively) add one to their arguments or subtract one from their arguments, so they’re known (also respectively) as the increment and decrement operators. Because they’re dependent upon numbers that can be counted, they’re limited to non-floating point variables. For example, the value of var after executing the following expression is 11:

int var = 10;   // initalize var
var++;          // now increment it
                // value of var is now 11

If you are wondering why a separate increment operator needs to be defined, the answer is that the authors of C++ noted that programmers add 1 more than any other constant. To provide some convenience, a special add 1 instruction was added to the language. In addition, most present-day computer processors have an increment instruction that is faster than the addition instruction.

Back when C++ was created — with microprocessors being what they were — saving a few instructions was a big deal. Today, not so much.

The increment and decrement operators are peculiar in that both come in two flavors: a prefix version and a postfix version (known as pre-increment and post-increment, respectively). Consider, for example, the increment operator (the decrement works in the same way).

Suppose that the variable n has the value 5. Both ++n and n++ increment n to the value 6. The difference between the two is that the value of ++n is the value after incrementing (6) while the value of n++ is the value before incrementing (5). The following example illustrates this difference:

// declare three integer variables
int n1, n2, n3;
n1 = 5;
n2 = ++n1; // the value of both n1 and n2 is now 6
n1 = 5;
n3 = n1++;// the value of n1 is 6 but the value of n3 is 5

Thus n2 is given the value of n1 after n1 has been incremented (using the pre-increment operator), whereas n3 gets the value of n1 before it is incremented using the post-increment operator.