I was working with some friends on some unit testing when we recently ran across an issue that was caused by an uninteded use of an incrementor (++). It was  quick fix but it is also something I have seen quite often, so I figured I would jot my thoughts down while it was fresh in my mind.

So we've all seen the common for loop in .NET, looping a finite number of times.

            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(i.ToString());
            }

This above example outputs a list of numbers 0 through 9. And at times we need to loop through one variable (like i in the above example) yet increment another counter variable. So we do something like the below example:

            int j = 0;
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine((j++).ToString());
            }

Nothing wrong with this. It loops 10 times and increments j. This above snippet outputs a list of numbers 0 through 9.

I recently was asked to debug some code that looked a little more like this:

            int k = 0;
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine((++k).ToString());
            }

Again, it loops a finite number of times (10) and increments a separate counter variable (k in this case). But this time the out put is slightly different than the previous 2 examples. This code snippet outputs 1 - 10. The reason is obvious when you strip out all of the other code that was there already ... the incrementor (++) appears before the k in this example. Thus, k is incremented, then the ToString() method operates on it. In the previous example, j variable's value is output and THEN the incrementor (++) operates on the j variable.

Not difficult to see in this case, of course. But the developer who was working on this was assured that x++ and ++x always responded the same, no matter the situation. Well, in MANY cases this is true. The above example could be modified so the incrementor preceeding or following the varialbe won't matter ... like either of these following code samples:

            int x = 0;
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(x.ToString());
                x++;
            }
 
            int y = 0;
            for (int i = 0; i < 10; i++)
            {
                Console.WriteLine(y.ToString());
                ++y;
            }

Both of these samples output 0-9 ... and both of these are much easier to read and less apt to wreak havoc than the previous inline examples.

OK, I am running out of letters for examples, gotta run!