"Break" and other ways out of loops and switches

Henry Spencer henry at utzoo.UUCP
Sun Aug 28 14:49:57 AEST 1983


I take a somewhat different approach to the argument about whether
it's better to use flags or "break n" to get out of multiple control
structures.  It does happen sometimes that I am in the middle of
multiple nested control structures and I want to get out several levels.
When this happens to me, I have learned to think:  "Stop!  This nesting
is too complex!  Break some of it out into subsidiary functions!".  The
result invariably seems to be cleaner, simpler code.  This has all the
obvious useful side effects, like less debugging and easier changes
later on.

In short, it doesn't matter what the answer is if you're asking
the wrong question.  Procedures are the most important control structure
in almost any programming language, and the most under-rated.  How many
times have you heard people complain about the logic of a procedure
being too complex?  Have you *ever* heard people complain about a
procedure being too simple?

I don't say that better decomposition into procedures ("functions"
in C) will solve all control-structure problems.  But my own experience
suggests that it will solve a lot of them, to the point where I am
continually unhappy that our beloved schools don't do a better job
of teaching it.  (My opinion is that procedures should be taught before
loops and before ifs and even before assignment statements -- they are
that important and that fundamental.)

If you object that it's inefficient to do this because of C's call
overhead, I suggest you listen more carefully to what you are saying.
Personally, I find it much easier to make a working program more
efficient than to try to debug an "efficient" ball of hair.  Plus
I don't have to do it as often, since the "inefficient" approach
often turns out to be good enough anyway.

More generally, I find it useful to listen very carefully for that
little voice that says "Stop!  It's too complex!  You're starting
to have trouble keeping track of it all!  Rethink it, now, before
you type another line!"  The more listening I do, the more I break
things down into the simplest functions I can think of.  My code is
better for it, and it's been years since I had any interest in using
a goto.  (Note, not "years since I used a goto", but "years since I
wanted to use one".  The difference is important.)
-- 
				Henry Spencer @ U of Toronto Zoology
				{allegra,ihnp4,linus,decvax}!utzoo!henry



More information about the Comp.lang.c mailing list