#54 – Increment and Decrement Operators

The increment operator (++) increments its operand by 1.  It’s a shorthand for using the binary + operator with an operand of 1.

 int n1 = 5;
 n1 = n1 + 1;     // Incrementing using +, n1 now 6
 n1++;            // Incrementing using ++, n1 now 7

You can also use the increment operator on the right-hand side of an expression.  In the example below, n1 is incremented after the expression is evaluated.

 n1 = 5;
 int n2 = 2 * n1++;   // n2 now 10, n1 is 6

Placing the ++ operator after the operand is known as postfix notation.  With prefix notation, the operator is placed before the operand, indicating the the variable should be incremented before the expression is evaluated.

 n1 = 5;
 n2 = 2 * ++n1;   // n2 now 12, n1 is 6

The decrement operator (- -) works similarly, decrementing the operand by 1.

 n1 = 5;
 n2 = 2 * n1--;   // n2 now 10, n1 is 4
Advertisements