©Conrad Weisert, Information Disciplines, Inc., 19 May 2008
During the structured revolution of the 1970s books and professional magazines were filled
with arguments and discussions of avoiding the notorious go to
statement. Some early structured coding practitioners devised schemes where an extra
switch was introduced in a search loop in order to record an event that might otherwise have
triggered a branch out of the loop. For example:
// Old fashioned code
// ------------------
for (ctr = 0; ctr < n; ++ctr)
{if (someCondition)
go to found;
}
go to notFound;
found:
take some action;
|
// Naive go-to-less version
// ------------------------
bool found = false;
for (ctr = 0; ctr < n; ++ctr)
{if (someCondition)
found = true;
}
if (found) take some action;
|
That got the argument started. What's wrong with the "structured" version? Critics immediately noted that the go-to-less version was inferior in three respects:
found is pure housekeeping
corresponding to nothing in the problem domain. It can distract the reader, especially if
the loop body were longer.
Here are two genuinely structured versions that avoid those shortcomings:
// Compact version
// ---------------
for (ctr = 0;
ctr < n && !someCondition;
++ctr) { }
if (ctr < n)
take some action;
|
// Explicit test version
// ---------------------
for (ctr = 0; ctr < n; ++ctr)
{if (someCondition)
break;
}
if (ctr < n)
take some action;
|
Note that if ctr is less than
n upon loop exit,
the value of ctr corresponds to the iteration during which
the condition was satisfied.
Although we thought the structured constructs idioms had been thoroughly debated and settled thirty years ago, today's students and even some practicing programmers are turning out code that ignores those idioms. Younger programmers may need to be reminded of some of them, including this one. |
Related information on this web site
|
Last modified October 4, 2008
Return to C++ topics
Return to technical articles
Return to Table of contents.