Here's a simple one, single for loop:
#define FOREACH(type, array, size) do { \
type it = array[0]; \
for(int i = 0; i < size; i++, it = array[i])
#define ENDFOR } while(0);
int array[] = { 1, 2, 3, 4, 5 };
FOREACH(int, array, 5)
{
printf("element: %d. index: %d\n", it, i);
}
ENDFOR
Gives you access to the index should you want it (i
) and the current item we're iterating over (it
). Note you might have naming issues when nesting loops, you can make the item and index names be parameters to the macro.
Edit: Here's a modified version of the accepted answer foreach
. Lets you specify the start
index, the size
so that it works on decayed arrays (pointers), no need for int*
and changed count != size
to i < size
just in case the user accidentally modifies 'i' to be bigger than size
and get stuck in an infinite loop.
#define FOREACH(item, array, start, size)\
for(int i = start, keep = 1;\
keep && i < size;\
keep = !keep, i++)\
for (item = array[i]; keep; keep = !keep)
int array[] = { 1, 2, 3, 4, 5 };
FOREACH(int x, array, 2, 5)
printf("index: %d. element: %d\n", i, x);
Output:
index: 2. element: 3
index: 3. element: 4
index: 4. element: 5