#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
Advertisement

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #54 – Increment and Decrement Operators

  1. kai zhou says:

    Nice work, Sean, thank you.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: