Last active
April 30, 2023 16:28
-
-
Save Hypnotriod/40ecc00095daef75e11532873b5a953c to your computer and use it in GitHub Desktop.
C99 foreach macro for fixed size array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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