Monday, October 22, 2007

On Prefix and Postfix Increment Operators

For those familiar with increment operators and their prefix and postfix usage skip down to just below the pseudo-code.

When you have a number and you want to increment it while stepping through a collection or something you can use the increment operator ("++"). That will add one to whatever number you pair with the operator. When using increment operators there are prefix and postfix forms. The prefix form is when you put the operator before the variable containing the number and the postfix is afterwards (++i vs. i++). Functionally these the placement results in very different functionality, if you use the prefix form then the number is incremented before it is evaluated whereas if you use postfix then it is evaluated after it's value is used. In other words (this is really simplified pseudo-code):

variable n = 0;
print n;
print n;

Will print the number 00.

variable n = 0;
print ++n;
print n;

Will print 11.

variable n = 0;
print n++;
print n;

Will print 01.

Awesome, let's continue.

The issue I have with this is that I can only use one at a time. I just came across a scenario where I actually got kind of excited about a line of code I had just written (which doesn't happen very often). The scenario was that I had a string containing tokens I needed however each token I needed was surrounded on both sides by tokens that I don't need. So I had something like:


This led me to writing the following lines of code:

for (int i = 0; i < tokens.Length; i++) {
  string token = tokens[++i++];
  Trace("Found Token: " + token);

Sadly the compiler informed me that what I had done is totally not allowed. Which made me sad. Because ++i++ looks awesome. And yes, I do realize that I'm a huge dork.

1 comment:

  1. Hi, Casey. Saturday nights are apparently my web surfing time -- as opposed to night on the town time. I saw your blog on linkedin and thought I'd catch up. Good to hear you're keeping busy and congratulations on kidlet #2. If you haven't read "Your Money or Your Life" yet, I highly recommend it. Take care, Christy.