Mobile Software Engineering

2007-10-10 by tamberg

Iterating Array Elements Backwards

To illustrate the sort of nit-picking we spend our energy on, consider this example from back in the days when we programmed in Component Pascal and foreach was not an option (example in C#).

Given an array

object[] a;

A straight forward approach to iterate through it would be

int i = 0;
while (i < a.Length) {
  Process(a[i]);
  i++;
}

Preventing multiple calls to the property method a.Length leads to

int i = 0;
int n = a.Length;
while (i < n) {
  Process(a[i]);
  i++;
}

If there's no fixed processing order we can further eliminate a variable

int n = a.Length - 1;
while (n >= 0) {
  Process(a[n]);
  n--;
}

And finally, reordering the decrement we can get rid of the ugly -1 and >=

int n = a.Length;
while (n > 0) {
  n--;
  Process(a[n]);
}

The latter two examples use the variable name n rather than i to emphasize the iteration direction.