Solved

C# increment and decrement operators

Posted on 2009-05-10
6
580 Views
Last Modified: 2012-05-06
I'm just starting to read a C# book.  I would like to find out why running a program gave me the results it did.

/* This is a program that I'm writing
   to see if I can figure out */

class TryThis
{

  public static void Main()
  {

    // postfix increment
    int length = 3;
    int newLength = length++;
    System.Console.WriteLine("Postfix increment example");
    System.Console.WriteLine("length = " + length);
    System.Console.WriteLine("newLength = " + newLength);

    // prefix increment
    length = 3;
    newLength = ++length;
    System.Console.WriteLine("Prefix increment example");
    System.Console.WriteLine("length = " + length);
    System.Console.WriteLine("newLength = " + newLength);

    // postfix decrement
    length = 3;
    newLength = length--;
    System.Console.WriteLine("Postfix decrement example");
    System.Console.WriteLine("length = " + length);
    System.Console.WriteLine("newLength = " + newLength);

    // prefix decrement
    length = 3;
    newLength = --length;
    System.Console.WriteLine("Prefix decrement example");
    System.Console.WriteLine("length = " + length);
    System.Console.WriteLine("newLength = " + newLength);

  }

}

This is the result:


C:\Documents and Settings>trythis
Postfix increment example
length = 4
newLength = 3
Prefix increment example
length = 4
newLength = 4
Postfix decrement example
length = 2
newLength = 3
Prefix decrement example
length = 2
newLength = 2

C:\Documents and Settings>

0
Comment
Question by:William Richardson
6 Comments
 
LVL 12

Expert Comment

by:geowrian
ID: 24351558
Postfix can be rewritten like this:
int length = 3;
int newLength = length;
length = length + 1;

Prefix can be rewritten like this:
length = 3;
length = length + 1;
newLength = length;

basically, anywhere you see a prefixed ++, you can perform that operation on a new line above it. Anywhere you see a postfixed ++, you can perform that operation immediately after it.
0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 24351618
Prefix notation (++variable/--variable) means that you increment a variable before you use it in the statement. Postfix notation (variable++/variable--) means that you use the variable, then you increment it.
int x = 1;
 

Console.WriteLine(++x);  // outputs 2 -- increment before use

Console.WriteLine(x++);  // outputs 2 -- use, then increment

Console.WriteLine(++x);  // outputs 3 -- increment before use
 

Console.WriteLine(x--);  // outputs 3 -- use, then decrement

Console.WriteLine(--x);  // outputs 1 -- decrement, then use

Open in new window

0
 
LVL 9

Expert Comment

by:tculler
ID: 24351630
Post/pre-fix inc/decrement operators are one of the most common sources of confusion for new programmers. The difference is extremely minimal, but the results can be catastrophic. For example, if I say the following:

int someNum1 = 50;
int someNum2 = someNum1++;

You would expect a call to
Console.WriteLine(someNum2);
to print out 51, correct? Actually, it will print out 50; however, if you print out someNum1 after that assignment, you'll find that it now holds 51.

The two main differences are as follows:
Pre-Inc/Decrement will evaluate the expression FIRST, and THEN assign the values. The operation
someNum2 = ++someNum1;
says add "1" to the variable called "someNum1", then takes it value, and copy it over to the variable called someNum2.

Post-Inc/Decrement will evaluate the expression AFTER the assigning the values. The operation
someNum2 = someNum1++;
says copy the value of the variable called someNum1 to the variable called someNum2. Then, AFTER this is done, add 1 to the value of the variable called someNum1.

However, this gets even more tricky. All this stuff just comes back to "operator precedence". The post-inc/decrement operators have a very low precedence, meaning that they are evaluated very late. Their precedence is so low, they are evaluated even AFTER the assignment has taken place! However, remember that parentheses () will force evaluation of their containing expression. So, contrary to what you'd expect, the following series of statements:

int someNum1 = 50;
int someNum2 = (someNum1++);
Console.WriteLine(someNum2.ToString());

Will actually display 51 to the screen. This is because the parentheses on the second line forces the evaluation of someNum1 BEFORE assigning its value.

This isn't as scary as it sounds, hang in there :)
Hope I helped,
Nate
0
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:William Richardson
ID: 24354865
length = 3;
    newLength = ++length;

Prefix increment example
length = 4
newLength = 4

On the expression newLength = ++length; is length getting a new value assigned to it with the prefix increment?  And when you have the a prefix increment/decrement is the precedence just taking place with the prefix first because there are two operators next to each other?  And with postfix increment/decrement is it just taking the value over the assignment operator before it assigns the incremented/decremented value to length?

0
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 24355305
Don't think of postfix/prefix notation as two operators--it is one operator. In your most recent example, because you are using prefix notation (++ before the variable), the variable "length" will be incremented, then assigned to the variable "newLength."
0
 
LVL 74

Accepted Solution

by:
käµfm³d   👽 earned 75 total points
ID: 24355336
Think of prefix notation like: I want to increase/decrease the current value before I use it.

Think of postfix notation like: I want to use the current value, then increase/decrease it
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Illustrator's Shape Builder tool will let you combine shapes visually and interactively. This video shows the Mac version, but the tool works the same way in Windows. To follow along with this video, you can draw your own shapes or download the file…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now