Skip to content

Instantly share code, notes, and snippets.

@multun
Last active December 12, 2017 14:37
Show Gist options
  • Save multun/e5512dd113632241c0cea1b5d5fcfca4 to your computer and use it in GitHub Desktop.
Save multun/e5512dd113632241c0cea1b5d5fcfca4 to your computer and use it in GitHub Desktop.
An array iterator in C
#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);
}
@multun
Copy link
Author

multun commented Dec 12, 2017

One may want to add a static assert to avoid "iterating" over a pointer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment