Last active
December 12, 2017 14:37
-
-
Save multun/e5512dd113632241c0cea1b5d5fcfca4 to your computer and use it in GitHub Desktop.
An array iterator in C
This file contains 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
#include <stddef.h> | |
#include <stdio.h> | |
#define ARR_SIZE(...) (sizeof(__VA_ARGS__) / sizeof((__VA_ARGS__)[0])) | |
#define FOREACH_ARR(Type, IName, ...) \ | |
for (struct \ | |
{ \ | |
size_t i; \ | |
Type v; \ | |
Type *arr; \ | |
} IName = \ | |
{ \ | |
0, \ | |
(Type[])__VA_ARGS__[0], \ | |
(Type[])__VA_ARGS__ \ | |
}; \ | |
IName.i < ARR_SIZE((Type[])__VA_ARGS__); \ | |
++IName.i, (IName.i >= ARR_SIZE((Type[])__VA_ARGS__)) \ | |
|| (IName.v = IName.arr[IName.i])) | |
int main(void) | |
{ | |
FOREACH_ARR(int, iter, {1, 2}) | |
printf("%d\n", iter.v); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One may want to add a static assert to avoid "iterating" over a pointer