GNOME Bugzilla – Bug 738609
Add g_list_for convenience macro
Last modified: 2014-10-16 10:33:55 UTC
I often have to iterate through the whole list but setting up a callback function and a data structure to emulate a closure is very inconvenient for simple one-off actions. This patch adds a `g_list_for` macro that uses a pre-defined iterator `it` to iterate over the list. In the "body" of that for-loop the user can simply dereference `it->data` to his liking.
Created attachment 288653 [details] [review] Add a g_list_for convenience macro
Review of attachment 288653 [details] [review]: ::: glib/glist.c @@ +162,3 @@ + * g_list_for (list, it) { + * g_print ("element: %s\n", (gchar *) it->data); + * } You could add since flag (easy to forget later), and update glib-sections.txt ::: glib/glist.h @@ +148,3 @@ #define g_list_next(list) ((list) ? (((GList *)(list))->next) : NULL) +#define g_list_for(list, it) for (it = g_list_first ((GList *)(list)); \ g_list_foreach() doesn't start from first element and supports removing current item. I think it should follow the same behaviour (you could have local _next variable) or at least warn usage in documentation.
Created attachment 288664 [details] [review] Incorporate suggestions by Marc-Andre Lureau. `g_list_for` now starts from whatever list is passed to it. The `g_list_for` symbol is added to `glib-sections.txt` and a `Since: 2.44` is added to the docstring. Furthermore, the docs discourage removing elements during an iteration.
(In reply to comment #2) > > g_list_foreach() doesn't start from first element and supports removing current > item. I think it should follow the same behaviour (you could have local _next > variable) or at least warn usage in documentation. Out of curiousity: how would I (without global state) mess with the list when inside the callback function of g_list_foreach? I now opted for the warning because g_list_for being a macro makes it difficult to avoid name clashes for the next variable.
We've usually rejected patches like this in the past for reasons of being too magical -- it's almost always better to open-code in situations like this and the macro saves only a little typing. Unless someone else strongly disagrees with this point, I'm going to close this as WONTFIX. Sorry :/