Bodyless loop (was: Comparing strings...)

Karl Heuer karl at haddock.ima.isc.com
Fri Oct 19 06:51:19 AEST 1990


Style wars beginning.  Hit 'n' now.

In article <1990Oct15.042851.18595 at zoo.toronto.edu> henry at zoo.toronto.edu (Henry Spencer) writes:
>In article <3343 at idunno.Princeton.EDU> pfalstad at drops.Princeton.EDU (Paul John Falstad) writes:
>>	while(...);
>
>By the way, tacking the ";" on the end of the while is a great way to
>trip up your readers...

This is a valid concern.  On the other hand, there are those of us who gag at
the sight of a naked semicolon on a line by itself, which is what I guess
Henry to be suggesting as an alternative.

Some time ago I adopted the convention of writing bodyless loops as
	do; while (...);
so that it's impossible to accidentally leave out the final semicolon.  This
produced an immediate bonus in that it often revealed a further transformation
that simplified the code:
	while ((rpid = wait(&status)) != pid);
==>	do; while ((rpid = wait(&status)) != pid);
==>	do rpid = wait(&status); while (rpid != pid);

The use of an assignment as a subexpression of a condition is only necessary
for test-at-top loops; thinking of it as a test-at-bottom loop eliminates the
need.  (This assumes that, all else being equal, "a=b; if (P(a))" is better
than "if (P(a=b))".  That leads back to the ":= vs = vs ==" wars, which should
probably go to comp.lang.misc.)

Exercise: evaluate each of the forms below (insert newlines according to your
personal style) and rank them according to susceptibility to disastrous typo
and/or reader misunderstanding.  Send your results by USmail to the person
whose name is immediately under yours in the Phone book.
	while (...);
	while (...) /* nothing */;
	while (...) {}
	while (...) continue;
	do; while (...);
	do /* nothing */; while (...);

Karl W. Z. Heuer (karl at ima.isc.com or uunet!ima!karl), The Walking Lint



More information about the Comp.lang.c mailing list