2008 07 17Loving the for
Early on in my programming life, I decided on a specific use for each iterator which became the doxa I never deviated from :
- for I know the quantity of stuff to iterate,
for (i=0; i<count; i++)
will do just fine - while I don't know what I'm getting, I'll be getting it while it's there :
while (node) { ... node = node->next }
One nice thing with for is that you can skip to the next element with continue :
for (i=0; i<count; i++) { element = array[i] if (!someConditionOnElement) continue compute ! }
Using while you need to open a brace to go through your condition and not skip the next element code node->next
:
node = firstNode while (node) { if (someConditionOnNode) { compute ! } node = node->next }
Clunky ! But … opening one more brace can be avoided when looking back at the initial form of for :
for (initialization; condition; nextElement)
All these 3 are expressions : you can use operators, function calls, arithmetic, or the Comma Trick for multiple expressions separated by a comma — but not statements. That way we can fix our while to put the next element code in the for :
for (node=firstNode; node; node=node->next) { if (!someConditionOnNode) continue compute ! }Cleaner and shorter !
Patrick Geiller
2008 07 18
Indeed, but you have to repeat the condition :( which may be more complicated than if (node)
.
You could also use a
do while
loop:Note that this doesn't test for
node
being non-NULL
initially. To do this you could probably just stick anif
statement before like: