Skip to content

Instantly share code, notes, and snippets.

@Hypnotriod
Last active April 30, 2023 16:28
Show Gist options
  • Save Hypnotriod/40ecc00095daef75e11532873b5a953c to your computer and use it in GitHub Desktop.
Save Hypnotriod/40ecc00095daef75e11532873b5a953c to your computer and use it in GitHub Desktop.
C99 foreach macro for fixed size array
// Declaration:
#define foreach(item, array) \
for (item = &array[0]; item != &array[sizeof(array) / sizeof(array[0])]; item++)
#define foreach_i(item, index, array) \
for (item = &array[0], index = 0; item != &array[sizeof(array) / sizeof(array[0])]; item++, index++)
#define foreach_l(item, array, length) \
for (item = &array[0]; item != &array[length]; item++)
#define foreach_il(item, index, array, length) \
for (item = &array[0], index = 0; item != &array[length]; item++, index++)
// Usage:
Vector2 testArray[] = {{1.f, 2.f}, {3.f, 4.f}, {5.f, 6.f}, {7.f, 8.f}};
Vector2 *item;
foreach(item, testArray)
{
printf("x: %f, y: %f\n", item->x, item->y);
}
Vector2 *pArr = testArray;
foreach_l(item, pArr, 4)
{
printf("x: %f, y: %f\n", item->x, item->y);
}
int index;
foreach_i(item, index, testArray)
{
printf("%d | x: %f, y: %f\n", index, item->x, item->y);
}
foreach_il(item, index, pArr, 4)
{
printf("%d | x: %f, y: %f\n", index, item->x, item->y);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment