Loving 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 !

Qwerty Denzel
2008 07 18

You could also use a do while loop:

node = firstNode;
do {
    if (! someConditionOnNode )
    compute !
} while ((node=node-&gt;next));

Note that this doesn't test for node being non-NULL initially. To do this you could probably just stick an if statement before like:

node = firstNode
if (node) do {
Patrick Geiller
2008 07 18

Indeed, but you have to repeat the condition :( which may be more complicated than if (node).

2008 07 18

For those who (like me) hadn't ever heard the word "doxa": it's the governing opinion, which is sublated through logos to episteme. Also a brand of watches. Wikipedia rules.

Follow me on Twitter
Planet Cocoa

2011 02 22Distance field
2010 07 202Binding through NSApp
2010 05 122Forwarding invocations
2010 02 272Core Image black fringes
2010 02 21Quickest Way to Shell
2010 02 08Who's calling ?
2009 09 2138 ways to use Blocks in Snow Leopard
2009 08 182Bracket Mess
2009 08 124Taming JavascriptCore within and without WebView
2009 04 15Debugging with Activity Monitor
2009 03 25How Core Image Color Tracking works
2009 03 1510Custom NSThemeFrame
2009 03 10Which framework is running ?
2009 03 074CoreUI can paint pretty big
2009 02 18Localization with functions
2009 01 30Did you forget to nest alloc and init?
2009 01 16JSCocoa on the iPhone
2009 01 11Mixing WebView and JavascriptCore
2009 01 09Badge overflow
2009 01 09Find your Garbage Collection leaks with Instruments

Powered by MediaWiki