The final word on GOTO (Don't I wis

Joe English jeenglis at nunki.usc.edu
Sat Sep 30 15:20:50 AEST 1989


[ Sorry if this is a repost; I forgot to expand the 
  tabs and cancelled the original as quick as I could... ]

kim at kim.misemi (Kim Letkeman) writes:
>If you examine almost any procedure of [large] size, you will see that it
>performs functions at two levels of control. Or even worse, two
>functions at the same level of control. Or really horrible, two
>completely independent functions at the same level of control where a
>switch passed in determines the action performed.
>
>As a general principle, writing a single procedure to perform a single
>function (task) is the whole point behind so called structured
>programming.  Coupling and cohesion and all that.
>
>So where does the goto fit after all this? It doesn't.


What kind of control flow you use doesn't have
that much to do with coupling or cohesion; the
goto still has some valid uses.  For example:


void foo() {
    int k;
    initialization_sequence;

    while (k = get_input()) {
      switch (k) {
        case 'A' : a_action(); break;
        case 'B' : b_action(); break; 
        ...
        case 'Q' : q_termination_stuff(); goto done;
        case 'X' : x_termination_stuff(); goto done; 
      }
      end_loop_processing;
    }
done:
    cleanup_sequence;

    return;
}

This, I submit, is an example of a cohesive function
that uses a goto. If end_loop_processing and
cleanup_sequence are nontrivial, this can't be cleanly
done any other way.

This example wasn't just invented to prove a point; I
actually wrote something similar once.  (I shouldn't
have said that...  now half the net will probably
accuse me of dubious programming practices :-)

Another example of (I think) a valid use for the
goto is the multi-level exception handling case
posted a while back.

--Joe English

  jeenglis at nunki.usc.edu



More information about the Comp.lang.c mailing list