How to implement FOREACH in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

struct Node
{
    int n;
    struct Node *next;
};

#define FOREACH(node, list) \
     for (node=list; node; node=node->next)

int main(void)
{
    struct Node *node, *list, **pplist = &list;

    for (int i = 0; i < 5; i++)
    {
         *pplist = malloc(sizeof(struct Node));
         (*pplist)->n = i;
         (*pplist)->next = NULL;
         pplist = &(*pplist)->next;
    }

    FOREACH(node, list)
    {
        printf("%d\n", node->n);
    }
    
    struct Node *current = list;
      
    while (current) 
    {
        current = current->next;
        free(list);
        list = current;
    }

    return 0;
}
   
/*
run:

0
1
2
3
4

*/

 



answered Jul 29, 2017 by avibootz
edited Jul 29, 2017 by avibootz
...