Always use braces (was: Suggested new C loop syntax)

Mark A Terribile mat at mole-end.UUCP
Tue Dec 27 13:23:32 AEST 1988


: : ... helping out a freshman CS major with her C homework [I] found out ...
: : that the teacher ... was marking off points for code which [used] braces
: : when they weren't strictly required.  They were teaching her to write ...:
: :
: :       inchar = getchar ();
: :       while (inchar != EOF)
: :               if (inchar == 0)
: :                       goto done;
: :               else
: :                       inchar = getchar ();
: : done: return inchar;
: :
: : Ickkk!!!
: Double Ickkkk!!!! A goto where a break would have done.

Let's see how many violations of good form we can see.

There's the use of a goto, period.
There's the use of a goto where a break would serve.
There's the use of an else after a goto or break.  (Some would praise this.
	I don't.  See the example on p. 45 of Kernighan and Plaugher, *The
	Elements of Programming Style*, featuring the label ``NEXT_C'' .
	It's a splendid example of dead-spot-in-code-before-else.)
There's the use of a goto to break multiple levels of structure without
	closing braces to remind the reader how many levels are being broken.
There are two seperate calls to getchar() at opposite ends of the loop, one
	for the first pass, and one for all subsequent passes.
There are two adjacent levels of control structure, both omitting braces.  This
	is not only a readability disaster, but a maintainance nightmare.
There's the use of a goto and label to fold surruptitiously two exits from the
	loop into one.  It's really tough to see at a glance both the goto-exit
	and the loop's natural exit-from-the-top.
There's the use of a `` goto X; ... X: return y; ''  If the purpose of the
	loop is to return a value at a certain point, then the return ought to
	be right in the loop, with the bottom exit return a special case.
There's the treatment of two effectively symmetrical cases in vastly different
	ways--return on EOF by the loop's control clause, and return on value
	zero by a goto, and what is worse, a goto that purports (by it's
	placement in the if-else) to be coordinate (rather than subordinate or
	superior) to the loop-continuation operation.

Whew!  That's enough for the moment.  I'd deem it a favor to future generations
of programmers and to the industry as a whole if someone would collect the
responses from the net and mail them to the wall-eyed buzzard, and to that
buzzard's superiors.  And I'll bet a very nice dinner that I've written more
code for which customers ultimately paid real dollars than he has.
-- 

(This man's opinions are his own.)
>From mole-end				Mark Terribile



More information about the Comp.lang.c mailing list