C: Multidimensional Loops

I am always looking for ways to make code more readable. Keeping the code terse yet clear. One kind of code I wanted to optimize was specific, partial looping on a multidimensional array. My example is that where you want to check adjacent positions in a 2D array. Previously I would have done something like the following:

int pos[2] = {0, 0}; // the base position

// perform the check on adjacent squares
int i, x, y;
for (i = 0; i < 4; i++) {
  switch (i) {
    case 0:
      x = -1; y = 0; break;
    case 1:
      x = 0; y = -1; break;
    case 2:
      x = 1; y = 0; break;
    case 3:
      x = 0; y = 1; break;
  }
  x += pos[0]; y += pos[1];

  // perform bounds check
  ...

  // perform the desired check
  ...
}

I have also seen other people's code which had a similar setup. As a big Python user for the last two years, I would express the above in a more terse fashion in Python:

base = (0, 0)

# perform the check on adjacent squares
for direction in ((-1,0), (0,-1), (1,0), (0,1)):
  x, y = direction + base
  # perform bounds check
  ...

  # perform the desired check
  ...

So now instead of 11 lines, we have 2 performing the looping. Yay Python! But we can do better in C and with something similar in nature to the python snippet:

int pos[2] = {0, 0};  // the base position

int i, x, y,
  // the adjacent directions
  dir[4][2] = {{-1,0}, {0,-1}, {1,0}, {0,1}};

// perform the check on adjacent squares
for (i = 0; i < 4; i++) {
  x = pos[0] + dir[i][0]; y = pos[1] + dir[i][1];  // unpack
  // perform bounds check
  ...

  // perform the desired check
  ...
}

This does apply quite well to multidimensional arrays. We can also use it for arrays of a single dimension if we needed to step over the array in an irregular way.

posted at: Mon, 16 Mar 2009 00:25 | path: /cplusplus | permanent link to this entry