I thought I'd post this here. It's a little function that I added while porting the struct loc refactoring to PWMAngband to make some code clearer. Here it is:
Code:
bool loc_iterator(struct loc *iter, struct loc *grid1, struct loc *grid2, bool strict)
{
iter->x++;
if (iter->x == (strict? grid2->x: grid2->x + 1))
{
iter->x = grid1->x;
iter->y++;
if (iter->y == (strict? grid2->y: grid2->y + 1)) return false;
}
return true;
}
This allows to change the following code:
Code:
for (y = y1; y < y2; y++) {
for (x = x1; x < x2; x++) {
foo(y, x);
}
}
into:
Code:
loc_copy(&iter, &grid1);
do {
foo(&iter);
} while (loc_iterator(&iter, &grid1, &grid2, true)); (or "false" to do "<=" instead of "<")
I've removed most of the ugly x/y loops that way.