The Mythical ++ Situation: ++ vs +=1

So this may be a post that most good programmers will think, “Well duh” but as I’m a tool this finally caught me.

I’d always heard that ++ evaluates differently than +=1, but I’d never run into a situation that would turn the old light bulb on so I really didn’t care. Well I met that situation today.

I was writing a method that basically checks to see if all the dates in a list are in order by creating a dictionary, assigning the index as the key, and sorting by the date. I then convert the keys to an array and make sure that the index is the same as the key. After all, if the dates are in order, the keys should mimic an index.

  Key     Date
  0        6-27-2008
  1        6-28-2008
  2        6-29-2008

So that the new array would be:

  [0]    0
  [1]    1
  [2]    2

And if anything was out of order, you would get something like this:

  [0]    0
  [1]    2
  [2]    1

So the code is basically:

  int loopCounter = -1;

  IDictionary<DateTime> timeSequence =
                .ToDictionary(item => loopCounter++);
  var sequenceList =
                 .OrderBy(item => item.Value)
                 .Select(item => item.Key).ToArray();
  return sequenceList.Any(item => item != sequenceList[item]);

Now right off the bat you’ll see that I used loopCounter ++. The thought was that in order to get this correctly inline (Meaning the key would mock an index) I would have to keep adding to the loopCounter. Well my thought was simply to use ++ and thus I would have to set the loopCounter to -1 at first otherwise the first key would be 1. Well that’s not what happened. Turned out it looked like:

  [0]  -1
  [1]   0
  [2]   1

Wait what? -1? But I added to it! And here was the catcher. Turns out in this situation, the ++ acts out like:

  • Set the key to what the loopCounter equals right now.
  • Add 1 too the loopCounter
  • Continue with loop

It actually set the key BEFORE adding the 1 to it. So in reality with this I really needed loopCounter to start at 0 OR use +=1 which would actually add the 1 THEN set the key to the value. Guess I should have paid more attention in school instead of checking NBA message boards.

Side note: Light bulb apparently is two words. I learned TWO things today.

2 thoughts on “The Mythical ++ Situation: ++ vs +=1”

  1. Or you could have used prefix operator instead of postfix. ++loopCounter instead of loopCounter++ then it would execute that before setting the index.

    1. That would have been good except I think this post sort of proves that my understanding of ++ was fundamentally flawed.

Comments are closed.