Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Does C have a “foreach” loop construct?

Does C have a “foreach” loop construct?

August 19, 2021 by James Palmer

C doesn’t have a foreach, but macros are frequently used to emulate that:
#define for_each_item(item, list)
for(T * item = list->head; item != NULL; item = item->next)

And can be used like
for_each_item(i, processes) {
i->wakeup();
}

Iteration over an array is also possible:
#define foreach(item, array)
for(int keep = 1,
count = 0,
size = sizeof (array) / sizeof *(array);
keep && count != size;
keep = !keep, count++)
for(item = (array) + count; keep; keep = !keep)

And can be used like
int values[] = { 1, 2, 3 };
foreach(int *v, values) {
printf(“value: %dn”, *v);
}

Edit: In case you are also interested in C++ solutions, C++ has a native for-each syntax called “range based for”

Here is a full program example of a for-each macro in C99:
#include

typedef struct list_node list_node;
struct list_node {
list_node *next;
void *data;
};

#define FOR_EACH(item, list)
for (list_node *(item) = (list); (item); (item) = (item)->next)

int
main(int argc, char *argv[])
{
list_node list[] = {
{ .next = &list[1], .data = “test 1” },
{ .next = &list[2], .data = “test 2” },
{ .next = NULL, .data = “test 3” }
};

FOR_EACH(item, list)
puts((char *) item->data);

return 0;
}

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in