C has 'for' and 'while' keywords. If a foreach statement in a language like C# looks like this ...
foreach (Element element in collection)
{
}
... then the equivalent of this foreach statement in C might be be like:
for (
Element* element = GetFirstElement(&collection);
element != 0;
element = GetNextElement(&collection, element)
)
{
//TODO: do something with this element instance ...
}
#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);
Here is what I use when I'm stuck with C. You can't use the same item name twice in the same scope, but that's not really an issue since not all of us get to use nice new compilers :(
#define FOREACH(type, item, array, size) \
size_t X(keep), X(i); \
type item; \
for (X(keep) = 1, X(i) = 0 ; X(i) < (size); X(keep) = !X(keep), X(i)++) \
for (item = (array)[X(i)]; X(keep); X(keep) = 0)
#define _foreach(item, array) FOREACH(__typeof__(array[0]), item, array, length(array))
#define foreach(item_in_array) _foreach(item_in_array)
#define in ,
#define length(array) (sizeof(array) / sizeof((array)[0]))
#define CAT(a, b) CAT_HELPER(a, b) /* Concatenate two symbols for macros! */
#define CAT_HELPER(a, b) a ## b
#define X(name) CAT(__##name, __LINE__) /* unique variable */
Usage:
int ints[] = {1, 2, 0, 3, 4};
foreach (i in ints) printf("%i", i);
/* can't use the same name in this scope anymore! */
foreach (x in ints) printf("%i", x);
EDIT: Here is an alternative for FOREACH using the c99 syntax to avoid namespace pollution:
While C does not have a for each construct, it has always had an idiomatic representation for one past the end of an array (&arr)[1]. This allows you to write a simple idiomatic for each loop as follows:
int arr[] = {1,2,3,4,5};
for(int *a = arr; a < (&arr)[1]; ++a)
printf("%d\n", *a);
As you probably already know, there's no "foreach"-style loop in C.
Although there are already tons of great macros provided here to work around this, maybe you'll find this macro useful:
// "length" is the length of the array.
#define each(item, array, length) \
(typeof(*(array)) *p = (array), (item) = *p; p < &((array)[length]); p++, (item) = *p)
...which can be used with for (as in for each (...)).
Advantages of this approach:
item is declared and incremented within the for statement (just like
in Python!).
Seems to work on any 1-dimensional array
All variables created in macro (p, item), aren't visible outside the
scope of the loop (since they're declared in the for loop header).
Disadvantages:
Doesn't work for multi-dimensional arrays
Relies on typeof(), which is a GNU extension, not part of standard C
Since it declares variables in the for loop header, it only works in C11 or later.
Just to save you some time, here's how you could test it:
typedef struct {
double x;
double y;
} Point;
int main(void) {
double some_nums[] = {4.2, 4.32, -9.9, 7.0};
for each (element, some_nums, 4)
printf("element = %lf\n", element);
int numbers[] = {4, 2, 99, -3, 54};
// Just demonstrating it can be used like a normal for loop
for each (number, numbers, 5) {
printf("number = %d\n", number);
if (number % 2 == 0)
printf("%d is even.\n", number);
}
char* dictionary[] = {"Hello", "World"};
for each (word, dictionary, 2)
printf("word = '%s'\n", word);
Point points[] = \{\{3.4, 4.2}, {9.9, 6.7}, {-9.8, 7.0}};
for each (point, points, 3)
printf("point = (%lf, %lf)\n", point.x, point.y);
/* Neither p, element, number or word are visible outside the scope of
their respective for loops. Try to see if these printfs work (they shouldn't): */
//printf("*p = %s", *p);
//printf("word = %s", word);
return 0;
}
Seems to work on gcc and clang by default; haven't tested other compilers.
C does not have an implementation of for-each. When parsing an array as a point the receiver does not know how long the array is, thus there is no way to tell when you reach the end of the array.
Remember, in C int* is a point to a memory address containing an int. There is no header object containing information about how many integers that are placed in sequence. Thus, the programmer needs to keep track of this.
However, for lists, it is easy to implement something that resembles a for-each loop.
for(Node* node = head; node; node = node.next) {
/* do your magic here */
}
To achieve something similar for arrays you can do one of two things.
use the first element to store the length of the array.
wrap the array in a struct which holds the length and a pointer to the array.
The following is an example of such struct:
typedef struct job_t {
int count;
int* arr;
} arr_t;
I defined foreach using a macro and helper function. It allows for nested cycles (although limited) and the item is only defined in scope of the cycle. The only problem is that the macro contains 2 statements, so no if(...) foreach(...) printf(...);, but I wouldn't recommend doing that with any statement.
You can probably improve it with the gnu typeof macro and the #define in ,, if you want.