#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

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

Follow

Get every new post delivered to your Inbox.

Join 43 other followers