Search code examples
for-loopwhile-loopreadability

Readability: list iteration with get_first/get_next, "while" vs. "for" loop


Let's say you would like to iterate trough a list using an initial get_first() with subsequent calls to get_next() which returns NULL at the end of the list.

Which one would you prefer reading?

element = get_first(list);
while (element)
{
    process(element);
    element = get_next(list);
}

vs.

for (element = get_first(list); element; element = get_next(list))
{
    process(element);
}

The state of an iteration is saved inside the list struct.

I am personally more used to the while version but when I saw someone use the for version I also easily understood what was going on so now I wonder which one is easier to read for most people.


Solution

  • Both are very readable. You won't confuse your readers with either. The while loop is arguably a bit more readable (But people mileage may vary...) so I would probably use it if the list was only iterated over once and use the more concise for loop otherwise.