Increment and Decrement Operators in C++

These operators also fall under the broad category of unary operators but are quite distinct than unary minus.

The increment and decrement operators are very useful in C++ language. They are extensively used in for and while loops. The syntax of these operators is given below:

++<variable name>
<variable name>++
--<variable name>
<variable name>--

The operator ++ adds 1 to the operand and -- subtracts 1 from the operand. These operators manifest in two forms: prefix and postfix.

For example, the ++ operator can be used in two ways:
++m and m++

These are two different expressions. The first expression immediately increments the value of m by 1. For example, the statements:

int t, m = 1;
t = ++m;

will cause the value of m to incremented first, and then this value is assigned to t, resulting in both having the same value.

On the other hand, the statements:

int t, m = 1;
t = m++;

will first evaluate the value of m (which is 1), resulting in 1 being assigned to t and then the value of m being incremented to 2.

The same case applies to decrement operator (--) too.

Precedence of Unary Operators:
(unary minus, increment and decrement operators)

Unary operators have a higher precedence than arithmetic operators. Hence, if a unary minus operator acts upon an arithmetic expression that contains one or more arithmetic operators, the unary minus operation will be carried out first (unless, of course, the arithmetic expression is enclosed in parentheses). Also, the associativity of the unary operators is right to left, though consecutive unary operators rarely appear in elementary programs.

You may also like...

1 Response

  1. August 11, 2013

    […] Increment and Decrement operators […]

Leave a Reply

Your email address will not be published. Required fields are marked *