[C-safe-secure-studygroup] Rule 15.5 review - goto must jump to a label declared later

Martin Sebor msebor at gmail.com
Wed May 30 16:52:53 BST 2018


The Rationale for Rule 15.2 - The goto statement shall jump to
a label declared later in the same function is summarized in
the following two paragraphs:

   Unconstrained use of goto can lead to programs that are
   unstructured and extremely difficult to understand.

   Restricting the use of goto so that “back” jumps are prohibited
   ensures that iteration only occurs if the iteration statements
   provided by the language are used, helping to minimize visual
   code complexity.

Many coding standards have rules against using goto at all on
the grounds that the statement tends to make code hard to read
(this goes as far back as Dijkstra's 1968 paper Go To Statement
Considered Harmful).  I agree that an excessive use of goto can
make code hard to follow, and I'm not sure that it matters much
whether the target of the statement is earlier or later in
the same function.  The instances of goto statements I can
think of are all forward jumps, either out of nested loops or
complex chains of conditionals, and sometimes to some common
cleanup "handler" toward the closing curly of the body of
the function executed just prior to returning from it.  So
intuitively, it seems like backward jumps might be less common,
but what bearing they might have on code readability is hard
to judge.  In the absence of data supporting the claim in
the Rationale I hesitate to take it at face value.

The second paragraph of the Rationale suggests that the rule
exists to avoid using goto as an iteration mechanism, and to
encourage the use of the existing iteration statements like
for and while.  That makes sense to me, but forbidding
backward jumps altogether seems like a roundabout way of
going about it.  Rather than seemingly arbitrarily restricting
the direction of goto statements I wonder if focusing the rule
on the problem ir seems to want to prevent would be a better
way to formulate it.  Say something like: avoid using goto
for iteration (with a clear definition of iteration of course).

Martin



More information about the C-safe-secure-studygroup mailing list