I am using GLib's doubly linked list structure, GList. I would like to know if there is any standard macro for iterating over a GList. I couldn't find any such thing in the GLib documentation. As a result I have made my own macro, but I'd rather use something standard if it exists.
To Illustrate the the issue: Usually I write a lot of code which looks like this:
GList *list, *elem;
MyType *item;
for(elem = list; elem; elem = elem->next) {
item = elem->data
/* do something with item */
}
With a macro it can be reduced to
GList *list;
MyType *item;
GFOREACH(item, list) {
/* do something with item */
}
Which is much less noisy.
Note: I realise GLib supplies a foreach function for iterating over a list and calling a callback for each element, but often the indirection of a callback makes the code harder to read, especially if the callback is only used once.
Update: seeing as there is no standard macro, I'm putting the macro I am using here in case it is of any use to someone else. Corrections/improvements are welcome.
#define GFOREACH(item, list) for(GList *__glist = list; __glist && (item = __glist->data, true); __glist = __glist->next)