knuth - 1974 - structured programming with go to statements

Upload: franck-dernoncourt

Post on 10-Apr-2018

275 views

Category:

Documents


6 download

TRANSCRIPT

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    1/41

    S t r u c t u r e d P r o g r a m m i n g w i t h g o t o S t a t e m e n t s

    D O N A L D E . K N U T H

    Stan ford Un iversity, Stan ford, Ca lifornia 9~S05

    A consideration of several different examples sheds new light on the problem of ereat-ing reliable, well-structured programs that behave efficiently. This study focuseslargely on two issues: (a) improved syntax for iterations and error exits, making itpossible to write a larger class of programs clearly and efficiently without g o t o state-ments; (b) a methodology of program design, beginning with readable and correct,but possibly inefficient programs that are systematically transformed if necessary into

    efficient and correct, but possibly less readable code. The discussion brings out op-posing points of view about whether or not g o t o statements should be abolished;some merit is found on both sides of this question. Fina!ly, an attempt is made todefine the true nature of structured programming, and to recommend fruitful direc-tions for further study.

    Keywords and phrases:structured programming, g o t o statements, language design,event indicators, recursion, Boolean variables, iteration, optimization of programs,program transformations, program manipulation systems searching, Quieksort,efficiency

    CR categories: 4.0, 4.10, 4.20, 5.20, 5.5, 6.1 (5.23, 5.24, 5.25, 5.27)

    You m ay go when you will go,And I will stay behind.

    - -Edna S t . Vincen t Mi l l ay[66]

    Most likely you go your way and I ' l l go mine.- -So ng title by Bob Dyla n[33]

    Do you suffer from painful elimination?- -Adver t i sement , J . B . Wi l l iams Co.

    INTRODUCTION

    A revolution is taking place in the way wewrite programs and teach programming, be-cause we are beginning to understand theassociated mental processes more deeply. Itis impossible to read the recent book Struc-tured programming [17; 55] without having it

    This research was supported in part by the Na-tional Science Foundation under grant numberGJ 36473X, and by IBM Corporation.

    change yo ur life. Th e reasons for this revolu-tion and its future prospects have been aptl ydescribed by E. W . D ijkst ra in his 1972 Tur-ing Award Lecture, "The Humble Program-mer" [27l.

    As we experience this revolution, each ofus na tural ly is developing strong feelings oneway or the other, as we agree or disagreewith the revolu tiona ry leaders. I must admi tto being a nomhumb le programmer , egotisti-

    Copyright (~) 1974, Association for Computing Machinery, Inc. General permission to republish,b u t not for profit, all or part of this material is granted, provided that ACM's copyright notice isgiven and that reference is made to this publication, to its date of issue, and to the fact that reprint-ing privileges were granted by permission of the Association for Computing Machinery.

    Comput ing Surveys , V?L 6 , No . 4 , Dee ,ember 1974

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    2/41

    2 6 2 , D o n a ld E . K n u t h

    C O N T E N T S

    I N T R O D U C T I O N1. E L I M I N AT I O N O Fs o t o S T AT E M E N T S

    H i s t o ri c a l B a c k g r o u n dA S e a r c h in g E x a m p l eEff ic iencyError E x i t sS u b s c r i p t C h e c k i n gH a s h C o d i n gTe x t S c a n n i n gA C onfe s s ion

    Tr e e S e a r c h i n gS y s t e m a t i c E l i m i n a t i o nE v e n t I n d i c a t o r sC o m p a r i s o n o f F e a t u r e sS i m p l e I t e r a t i o n s

    2 . IN T R O D U C T I O N O Fs o t o S T AT E M E N T SR e c u r s i o n E l i m i n a t i o nP r o g r a m M a n i p u l a t io n S y s te m sR e e u r s i o n v s . I t e r a t i o nB o o l e a n Va r i a b l e E l i m i n a t i o nC o r o u t i n e sQ u ick so r t : A D ig re s s io nA x i o m a t i c s o f J u m p sR e d u c t i o n o f C o m p l i c a t io n

    3 . C O N C L U S I O N SS t r u ct u r ed P r o g r a m m i n gW i t h go to S t a t e m e n t sEff ic iencyT h e F u t u r e

    A C K N O W L E D G M E N T SA P P E N D I XB I B L I O G R A P H Y

    eal enough to believe that my own opinionsof the current treads are not a waste of thereader's time. Therefore I want to express inthis article several i of the things that struckme most forcefully as I have been thinkingabout structured programming during thelast year; several of my blind spots were re-moved as I ivas learning these things, and Ihope I can convey some of my excitement tothe reader. Hardly any of the ideas I willdiscuss are my own; they are nearly all thework of others, but perhaps I may be pre-senting them in a new light. I write thisarticle in the first person to emphasize thefact that what I'm saying is just one man'sopinion; I don' t expect to persuade everyonethat my present views are correct.

    Before beginning a more technical discus-sion. I should confess that the title of thisarticle was chosen primarily to generateattention. There are doubtless some readerswho are convinced that abolition of go t ostatements is merely a fad. and they may seethis title and think, "Aha! Knuth is rehabili-tating the go to statement, and we can go

    back to our old ways of programmingagain." Another class of readers will see theheretical title and think, "When are die-hards like Knuth going to get with it?" Ihope that both classes of people will read onand discover that what I am really doing isstriving for a reasonably well balanced view-point about the proper role of go to state-ments. I argue for the elimination of go t o' sin certain cases, and for their introduction in

    others.I believe that by presenting such a view Iam not in fact disagreeing sharply withDijkstra's ideas, since he recently wrote thefollowing: "Please don't fall into the trap ofbelieving that I am terribly dogmaticalabout [the go to statement]. I have theuncomfortable feeling that others are makinga religion out of it, as if the conceptualproblems of programming could be solved bya single trick, by a simple form of codingdiscipline!" [29]. In other words, it, seemsthat fanatical advocates of the New Pro-gramming are going overboard in their strictenforcement of morality and purity inprograms. Sooner or later people are goingto find that their beautifully-structured

    C o m p u t i n g Surveys , Vo l . 6 , No . 4 , December 1974

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    3/41

    Structured Programming withg o t o S t a~ m e n t~!

    programs a re runn ing a t on ly ha l f t he speed- - o r w o r s e - - o f th e d i r t y o l d p r o g r a m s t h e yused to wr i te , and the y will mis t aken ly b lam ethe s t ruc tu re ins t ead o f r ecogn iz ing wha t i sp r o b a b l y t h e r e a l c u l p r i t - - t h e s y s t e m o v e r-h e a d c a u s e d b y t y p i c a l c o m p i le r im p l e m e n t a -t ion o f Boo lean va r i ab les an d p rocedu re ca ll s.T h e n w e ' l l h a v e a n u n f o r t u n a t e c o u n t e r -r evo lu tion , som eth ing like the cu r ren t r e jec -t io n o f t h e " N e w M a t h e m a t i c s " i n re a c t io nto i t s over-zea lous reforms.

    I t m a y b e h e l p f u l t o c o n s i d e r a f u r t h e rana logy wi th ma themat i c s . In 1904 , Ber t -r and Russe l l pub l i shed h i s f amous pa radoxa b o u t t h e s e t o f a l l s e t s w h i c h a r e n ' t m e m -

    bers o f themse lves . Th i s an t ino m y shook thefounda t ions o f c l a s s i ca l ma themat i ca l r ea -son ing , s ince i t appa ren t ly b rough t ve rys im p l e a n d o r d i n a r y d e d u c t i v e m e t h o d s i n t oques t ion . The ensuing cr i s i s led to the r i seof " in tu i t ionis t logic" , a school of thoughtc h a m p i o n e d e s p e ci al ly b y t h e D u t c h m a t h e -mat i c i an , L . E . J . Brouwer ; in tu i t ion i sma b a n d o n e d a ll d e d u c t i o n s t h a t w e r e b a se d o nques t ionab le noncons t ruc t ive ideas . For a

    whi l e i t appea red tha t in tu i t ion i s t l og icwould cause a r evo lu t ion in ma themat i c s .B u t t h e n e w a p p r o a c h a n g e r e d D a v i d H i l -b e r t , w h o w a s p e r h a p s t h e l e ad i ng m a t h e m a -t i c i a n o f t h e t i m e ; H i l b e r t s a i d t h a t " F o r-b i d d in g a m a t h e m a t i c i a n t o m a k e u s e of t h epr inc ip le of the excluded middle i s l ikefo rb idd ing an a s t ronom er h i s te l e scope o r aboxer the use o f h i s f i s t s . " He cha rac te r i zedthe in tu i t ion i s t approach as seek ing" tos a v e m a t h e m a t i c s b y t h r o w i n g o v e r b o a r da ll t h a t i s t r o u b le s o m e . . . T h e y w o u l d c h o pup and mang le the sc ience. I f we wou ldfo llow such a r e fo rm as they sugges t, wecou ld run the r i sk o f lo sing a g rea t p a r t o f ou rm o s t v a l u a b l e t r e a s u r e s " [ 8 0 , p p . 9 8 - 9 9 ,148-150, 154-157, 184-185, 268-270].

    Something a l i t t le l ike th is i s happeningin compute r sc i ence . In the l a t e 1960 ' s wewi tnessed a " so f tware c r i s i s " , wh ich manyp e o p l e t h o u g h t w a s p a r a d o x i c a l b e c a u s eprogramming was supposed to be so easy.As a resul t of the cr i s i s , people are now be-g inn ing to r enounce eve ry f ea tu re o f p ro -g r a m m i n g t h a t c a n b e c o n s i d e r e d g u i l t y b yvi r tu e of i t s associa t ion w i th d i ff icu l ties . N o to n l y g o t o s t a t e m e n t s a r e b e in g q u e s t io n e d ;

    * 2 6 3

    we a l so hea r com pla in t s ab ou t f loa t ing -po in tca lcula t ions , g loba l var iab les , semap hores ,po in te r va r i ab les , and even as s ignments t a te m e n t s . S o o n w e m i g h t b e r e s t r ic t e d t oon ly a dozen o r so p rograms tha t a re su ff i -c i en t ly s imple to be a l lowab le ; t hen we wi l lb e a l m o s t c e r t a i n t h a t t h e s e p r o g r a m sc a n n o t l e a d u s i n t o a n y t r o u b l e , b u t o fc o u r s e w e w o n ' t b e a b l e t o s o l v e m a n yprob lems .

    I n t h e m a t h e m a t i c a l e a se , w e k n o w w h a th a p p e n e d : T h e i n t u it io n i s ts t a u g h t t h e o t h e rm a t h e m a t i c i a n s a g r e a td e a l a b o u td e d u c t i v em e t h o d s , w h i l e t h e o t h e r m a t h e m a t i c i a n sc l e an e d u p t h e c la s si ca l m e t h o d s a n d e v e n -

    t u a l l y " w o n " t h e b a t t le . A n d a r e v o l u ti o nd id , i n f ac t , t ake p lace . In the compute rsc ience case , I imagine tha t a s imi lar th ingwi ll even tua l ly hap pen : pu r i s t s wi l l po in t theway to c l ean cons t ruc t ions , and o the r s wi l lf ind way s to pur i fy the i r u se o f f loa ting -po in ta r i thmet i c , po in te r va r i ab les , a s s ignment s ,e t c ., so tha t these c l a s si cal t oo l s can b e use dw i t h c o m p a r a t i v e s a f e t y.

    Of course a l l ana log ies b rea k down, inc lud-

    ing th i s one , e spec ia l ly s ince I 'm no t ye tc o n c e i t e d e n o u g h t o c o m p a r e m y s e l f t oD a v i d H i l b e r t . B u t I t h i n k i t ' s a n a m u s i n gc o i n c i d e n c e t h a t t h e p r e s e n t p r o g r a m m i n gr e v o l u ti o n is b e i n g l e d b y a n o t h e r D u t c h m a n( a l t h o u g h h e d o e s n ' t h a v e e x t r e m i s t v i e w scor respond ing to Brouwer ' s ) ; and I docons ide r a s s ignment s t a t emen t s and po in te rv a r i a b l e s t o b e a m o n g c o m p u t e r s c i e n c e ' s"mos t va luab le t r easu res ! ' .

    A t t h e p r e s e n t ti m e I t h i n k w e a re o n t h eve rge o f d i scover ing a t l a s t wha t p rogram-ming l anguages shou ld r ea l ly be l ike . I l ookfo rward to see ing many re spons ib le exper i -m e n t s w i t h l a n g u a g e d e si gn d u r i n g t h e n e x tf e w y e a r s; a n d m y d r e a m i s t h a t b y 1 98 4 w ewil l see a consensus developing for a rea l lygood p rogram m ing l angua ge (or, m ore l ike ly,a coheren t f am i ly o f l anguages ). F ur the r-more , I 'm guess ing tha t peop le wi l l becomes o d i s e n c h a n te d w i t h t h e l a n g u a g e s t h e y a r en o w u s i n g - - e v e n C O B O L a n d F O RTr A N - -th a t th is new language , UTOPXA84, wi ll hav ea c h a n c e t o t a k e o v e r. A t p r e s e n t w e a r e fa rf rom tha t goa l , ye t t he re a re ind ica t ionst h a t s u c h a l a n g u a g e i s v e r y s l o w l y t a k i n gshape .

    Co m puting Surveys, Vol. 6 , No. 4 ,D e c e m b e r 1 9 7 4

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    4/41

    264 Dona ld E . Knu th

    Will UTOPIA 84, or perhaps we should callit NEWSPEAK, contain go to sta tements? Atthe moment, unfortunately, there isn't evena consensus about this apparently trivialissue, and we had better not be hung up onthe question too much longer since there areonly ten yea rs left.

    I will try in what follows to give a reason-ably comprehensive survey of the go tocontroversy, arguing both pro and con, with-out taking a strong stand one way or theothe r until the discussion is nearly complete.In order to illustrate different uses of go tostatements, I will discuss many exampleprograms, some of which tend to negate the

    conclusions we might draw from the others.There are two reasons why I have chosen topresent the material in this apparentlyvacillating manner. First, since I have theopportunity to choose all the examples, Idon' t think it' s fair to load the dice by select-ing only program fragments which favor oneside of the argument. Second, and perhapsmost important, I tried this approach when Ilectured on the subject at UCLA in Feb-

    ruary, 1974, and it worked beautifully:nearly everybody in the audience had theillusion that I was largely supporting his orher views, regardless of what those viewswere !

    1. ELIMINATION OF go to STATEMENTS

    Historical Background

    At the IFIP Congress in 1971 I had thepleasure of meeting Dr. Eiichi Goto ofJapan, who cheerfully complained that hewas always being eliminated. Here is thehistory of the subject, as far as I have beenable to trace it.

    The first programmer who systematicallybegan to avoid all labels and go to state-ments was perhaps D. V. Schorre, then ofUCLA. H e has wri tten the following account

    of his ea rly experiences [85]:S i n c e t h e s u m m e r o f 19 60 , I h a v e b e e n w r i t i n gp r o g r a m s i n o u t l i n e f o rm , u s i n g c o n v e n t i o n s o fi n d e n t a t i o n t o i n d i c a t e t h e f lo w o f c o n t r o l . Ih a v e n e v e r f o u n d i t n e c e s s a r y t o t a k e e x c e p -t i o n t o t h e s e c o n v e n t i o n s b y u s i n gg o s t a t e -m e n t s . I u s e d t o k e e p t h e s e o u t l i n e s a s o r i g i n a l

    documentation of a program, instead of usingflow cha r ts . . . Then I would code the pro-gram in assembly language from the outline.Everyone liked these outlines better thant h e flow charts I had drawn before, whichw e r e not very neat--my flow charts had beennick-named "balloon-o-grams".

    He reported tha t this method made programseasier to plan, to modi fy and to check out.

    When I met Schorre in 1963, he told me ofhis radical ideas, and I didn't believe theywould work. In fact, I suspected that it wasreally his rationalization for not finding aneasy way to put labels and go to statementsinto his META-II subse t of ALGOL [84], alanguage which I liked ver y much except forthis omission. In 1964 I challenged him towrite a program for the eight-queens prob-lem without using go to statements, and heresponded with a program using recursiveprocedures and Boolean variables, ver y muchlike the program later published independ-ently by Wirth [96].

    I was still not convinced that all go t ostatements could or should be done awaywith, although I fully subscribed to PeterNaur's observations which had appearedabout the same time [73]. Since Naur 'scomments were the first published remarksabout harmful go to's, it is instructive toquote some of them here:

    If you look carefully you will find that surpris-ingly often a g o t o statement which looks backreally is a concealed fo r statement. And youwill be pleased to find how the clarity of thealgorithm improves when you insert the f o rclause where it belongs . . . If the purpose [ofa programming course] is to teach ALGOL pro-gramming, the use of flow diagrams will domore harm than good, in my opinion.

    The next year we find George Forsythealso purging go to statements from algo-rithms submitted to Communicat ions of theA C M (cf. [53]). Incidentally. the secondexample program at the end of the originalALGOL 60 r eport [72] conta ins four go t ostatements, to labels named AA, BB, CC,

    and DD, so it is clear tha t t he advantages ofALGOL'S control structures weren' t fullyperceived in 1960.

    In 1965, Edsger Dijkstra published thefollowing instructive remarks [21]:

    Tw o p r o g r a m m i n g d e p a r t m e n t m a n a g e r s f ro m

    Com puting Surveys, Vol. 6, No. 4,D e c e m b e r 1 9 7 4

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    5/41

    Structured Programming withgo to S ta t emen t s

    d i ff e r e n t c o u n t r ie s a n d d i f f e r e n t b a c k g r o u n d s- - t h e o n e m a i n l y s c ie n t if ic , t h e o t h e r m a i n l yc o m m e r c i a l - - h a v e c o m m u n i c a t e d t o m e , in -d e p e n d e n t l y o f e a c h o t h e r a n d o n t h e i r o w ni n i t ia t i v e , t h e i r o b s e r v a t i o n t h a t t h e q u a l i t yo f t h e i r p r o g r a m m e r s w a s i n v e r s e l y p r o p o r -

    t io n a l to t h e d e n s i ty o f g o t o s t a t e m e n t s i nt h e i r p r o g r a m s . . . . I h a v e d o n e v a r i o u s p r o -g r a m m i n g e x p e r i m e n t s . . , i n m o d if ie d v e r-s i o n s of A LG OL 6 0 i n w h i c h t h e g o t o s t a t e m e n tw a s a b o l is h e d . . . . T h e l a t t e r v e r s i o n s w e r em o r e d i f f ic u l t t o m a k e : w e a r e so f a m i l i a r w i t ht h e j u m p o r d e r t h a t i t r e q u i r e s so m e e f f o r t t of o r g e t i t ! I n a l l c a s e s t r i e d , h o w e v e r , t h ep r o g r a m w i t h o u t t h e g o to s t a t e m e n t t u r n e do u t t o b e s h o r t e r a n d m o r e lu c id .

    A f e w m o n t h s l a te r, a t t h e A C M P r o -g r a m m i n g L a n g u a g e s a n d P r a g m a t i c s C o n -fe rence , Pe te r Land in pu t i t t h i s way [59] :

    T h e r e i s a g a m e s o m e t i m e s p l a y e d w i t h A LG OL6 0 p r o g r a m s - - r e w r i t i n g t h e m s o a s t o a v o i du s i n g g o t o s t a t e m e n t s . I t i s p a r t o f a m o r ee m b r a c i n g g a m e - - r e d u c i n g t h e e x t e n t t ow h i c h t h e p r o g r a m c o n v e y s i ts i n f o r m a t i o n b ye x p l i c i t s e q u e n c i n g . . . . T h e g a m e ' s s i g n if i-c a n c e li e s i n t h a t i t f r e q u e n t l y p r o d u c e s am o r e " t r a n s p a r e n t " p r o gr a m - -- e a si e r t ou n d e r s t a n d , d e b u g , m o d i f y , a n d in c o r p o r a t ei n t o a l a r g e r p r o g r a m .

    Pe te r Naur r e in fo rced th i s op in ion a t t hesam e m eet ing [74 , p . 179].

    T h e n e x t c h a p t e r i n th e s t o r y is w h a t m a n ypeop le rega rd a s the f ir st , because i t m ade th em o s t w a v e s . D i j k s t r a s u b m i t t e d a s h o r tar t ic le to Communications of the ACM,de-vo ted en t i r e ly to a d i scussion o f go to s t a t e -mea t s . In o rde r to speed pub l i ca t ion , theed i to r dec ided to pub l i sh Di jks t r a ' s a r t i c l eas a le t te r, a nd to su pply a new t i tle ,"G o tos t a t emen t cons ide red ha rmfu l " . Th i s no te[23] rapid ly be cam e wel l -know n; i t expressedDi jks t r a ' s conv ic t ion tha t go to ' s " shou ldbe abol i shed f rom a l l 'h igher level ' p rogram-ming languages ( i .e . , everyth ing except ,p e r h ap s , p l ai n m a c h i n e c od e ) . . . . T h e g ot os t a t emen t a s i t s t ands i s ju s t t oo p r imi t ive ;i t is t oo muc h an inv i t a t ion to m ake a m ess o fo n e ' s p r o g r a m . " H e e n c o u r a g e d l o o k i n g f o ra l t e r n a t i v e c o n s t r u c t i o n s w h i c h m a y b e

    necessary to sa t i s fy a l l needs . Di jks t ra a lsoreca l l ed tha t He inz Zemanek had expressedd o u b t s a b o u t g o t o s t a t e m e n t s a s e a r l y a s1959 ; and tha t Pe te r Land in , Chr i s topherS t r a c h e y, C . A . R . H o a r e a n d o t h e r s h a dbeen o f some inf luence on h is th inking.

    2 6 5

    B y 1 96 7, t h e e n t i r e X P L c o m p i le r h a db e e n w r i t te n b y M c K e e m a n , H o m i n g , a n dW or tm an , us ing go to :on ly once ( [65] , pp .365-458 ; the go to i s on pag e 385). In 1971,C h r i s t o p h e r S t r a c h e y [ 87 ] r e p o r t e d t h a t " I t

    i s my a im to wr i t e p rograms wi th no l abe l s .I a m do ing qu i t e well. I ha ve go t the o pe ra t -ing sys tem down to 5 l abe l s and I am p lan -n ing to wr i t e a compi le r wi th no l abe l s a ta l l ." In 1972, an en t i re se s s ion o f the A C MN a t i o n a l C o n f e r en c e w a s d e v o t e d t o t h esub jec t [44 ; 60 ; 100] . T he D ecem ber, 1973,issue of Datamation f ea tu red f ive a r t i c l e sa b o u t s t r u c t u r e d p r o g r a m m i n g a n d e l i m i n a -t ion of go to 's [3; 13; 32; 64; 67]. Thu s, i t is

    c l ea r tha t s en t imen t s aga ins t go to s t a t e -men t s have been bu i ld ing up . In f ac t , t hed i scuss ion has apparen t ly caused somepeop le to f ee l t h rea ten ed ; D i jks t r a once to ldm e t h a t h e a c t u a l l y r e c e i v e d ' % t o r r e n t o fa b u s i v e l e t t e r s " a f t e r p u b l i c a t i o n o f h isarticle.

    Th e t ide o f opin ion f i r st h i t m e pe r sona l lyin 1969 , when I w as teach ing an in t rodu c to ryprogramming course fo r the f i r s t t ime . Ir emember f ee l ing f rus t r a t ed on seve ra loccas ions , a t not see ing how to wr i te pro-g r a m s i n t h e n e w s t y l e ; I w o u l d r u n t o B o bFlo yd 's off ice asking for he lp , and he usu al lys h o w e d m e w h a t t o d o . T h i s w a s t h e g e n e si sof our a r t ic le [52] in which w e presen ted tw ot y p e s o f p ro g r a m s w h i c h d id n o t s u b m i tg race fu l ly to th e new proh ib i t ion . W e foundt h a t t h e r e w a s n o w a y t o im p l e m e n t c e r ta i ns imple cons t ruc t ions wi th w h i l e a n d c o n d i -t io n a l g t a t e m e a t s s u b s t i t u t e d f o r g o t o ' s ,un les s ex t ra com puta t ion was speci fi ed .

    Du r ing th e l a s t f ew yea r s seve ra l languageshave appea red in which the des igne r sp r o u d l y a n n o u n c e d t h a t t h e y h a v e a b o l is h e dt h e g o t o s t a t e m e n t . P e r h a p s t h e m o s tp rom inen t o f these i s Bra ss [98] , wh ichor ig ina lly r ep laced go to ' s b y e igh t so -ca l led" e s c a p e " s t a t e m e n t s . A n d t h e e i g h t w e r e n ' te v e n e n o u g h ; t h e a u t h o r s w r o t e , " O u rmis take was in a s suming tha t the re i s no

    n e e d f o r a la b e l o n c e t h e g o t o i s r e m o v e d , "and the y l a t e r [99 , 100] adde d a new s t a t e -m e n t " l e a v e ( l a b e l )w i t h ( express ion)"which goes to the p laceafter t h e s t a t e m e n tiden t i f i ed by the ( l abe l ) . O the r go to - l e s sl a n g u a g e s f o r s y s t e m s p r o g r a m m i n g h a v e

    Computing Surveys, VoL 6, No. 4,December 1974

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    6/41

    266 Donald E . Knuth

    similarly introduced other statements whichprovide "equal ly powerful" alternative waysto jump.

    In other words, it seems th at there is wide-spread agreement tha t go t o statements areharmful, yet programmers and languagedesigners still feel the need for some euphe-mism that "goes to" without saying go to.

    A Searching ampMWhat are the reasons for this? In [52], Floydand I gave the following example of a typicalprogram for which the ordinary capabilitiesof w h i l e and if statements are inadequate.Let' s suppose tha t we want to search a table

    A[1] ... A[m] of distinct values, in order tofind where a given value x appears; if x is notpresent in the table, we want to insert it asan additional entry. Let's suppose furtherthat there is another array B, where B[,]equals the number of times we have searchedfor the value A[i]. We might solve such aproblem as follows:

    E x a m p l e 1 :

    f o r i : = 1 s t e p 1 u n t i l m d o .i f A [ i ] = x t h e n g o t o f o u n d f i ;

    n o t f o u n d : i : = r e + l ; m : = i ;A [ i ] : = x ; B [ i] : = 0 ;

    f o u n d : B [ i] : = B [ i ] + I ;

    (In the present article I shall use an ad hocprogramming language that is very similarto ALGOL 60, with one exception: the symbolfi is required as a closing bracket for all ifstatements, so that begin and end aren't

    needed between then and else. I don'treally like the looks of fi at the moment ; butit is short, performs a useful function, andconnotes finality, so I'm confidently hopingthat I'll get used to it. Alan Perlis has re-marked that tl is a perfect example of acryptic notation that can make program-ming unnecessarily complicated for begin-ners; yet I 'm more comfortable with fi everytime I write it. I still balk at spelling otherbasic symbols backwards, and so do most ofthe people I know; a student's paper con-taining the code fragment "esae; c o m m e n tbletch tnemmoc;" is a typical reaction tothis trend !)

    There are ways to express Example 1without go to statements, but they require

    more computation an.d aren't really moreperspicuous. Therefore, this example hasbeen widely quoted in defense of the go tostatement, and it is appropriate to scrutinizethe problem carefully.

    Let's suppose that we've been forbiddento use go to statements, and that we wantto do precisely the computation specified inExample 1 (using the obvious expansion ofsuch a for statement into assignments anda while iteration). If this means not onlythat we want the same results, but also thatwe want to do the same operations in thesame order, the mission is impossible. But ifwe are allowed to weaken the conditions

    just slightly, so that a relation can be testedtwice in succession (assuming th at it willyield the same result each time, i.e., that ithas no side-effects), we can solve the problemas follows:

    E x a m p l e l a :

    i : = 1 ;w h i l e i < m a n d A [ i ] # x d o i : - - i + 1 ;i f i > m t h e n r a : = i ; A [ i ] : = x ; B[i ] : := 0 f i ;B [ i ] : = B [ i ] + I ;

    The a n d operation used here stands forMcCa rthy 's sequential conjunction operator[62, p. 185]; i.e., "p and q" means " i f pt h e n q e l s e f a l s efl ", so that q is not evalu-ated when p is false. Example la will doexactly the same sequence of computationsas Example 1, except for one extra compari-son of i with m (and occasionally one lesscomputation of m + 1). If the iteration in this

    while loop is performed a large number oftimes, the extra comparison has a negligibleeffect on the running time.

    Thus, we can live without the go to inExample 1. But Example la is slightly lessreadable, in my opinion, as well as slightlyslower; so it isn't clear what we have gained.Furthermore, if we had made Example 1more complicated, the trick of going to Ex-ample la would no longer work. For ex-ample, suppose we had inserted anotherstatement into the for loop, just before thei f clause; then the relations i _< m andA[i] -- x wouldn' t have been tested consecu-tively, and we couldn't in general have com-bined them with and.

    John Cooke told me an instructive story

    Com puting Surveys, Vol. 6 , No. 4 , Decem ber 1974

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    7/41

    S t r u c tu r e d P r o g r a m m i n g w i t hg o t o , S t a ~ n e z d ~L

    r e l a t ing to Example 1 and to the des ign o fl an g u ag e s. S o m e P L / I p r o g r a m m e r s w e r easked to do the s t a t ed sea rch p rob lem wi th -o u t u s i n g j u m p s , a n d t h e y c a m e u p w i t hessent ia l ly the fo l lowing two solu t ions :

    a )

    b )

    D O I - 1 t o M W H I L E A ( I ) - ~ ffi X ;E N D ;

    I F I > M T H E ND O ; M z I ; A ( I ) = X ; B ( I ) ffi 0 ; E N D ;

    B ( I ) ffi B ( I ) + I ;F O U N D = 0 ;

    D O I - i T O M W H I L E F O U N D = 0 ;I F A ( I ) - X T H E N F O U N D = i ;

    E N D ;

    IF FOUND ffi 0 THEND O ; M - I ; A ( I ) = X ; B ( I ) ffi 0 ; E N D ;

    B ( I ) - B (I ) ffi 1 ;

    Solut ion (a) i s bes t , but s ince i t involves anul l i te ra t ion (wi th no expl ic i t s ta tementsbe ing i t e ra t ed ) mos t peop le came up wi thSo lu t ion (b ) . The ins t ruc t ive po in t i s t ha tSolu t ion (b) doesn ' t work; there i s a ser iousbug which caused g rea t puzz lemen t be fo ret h e r e a s o n w a s f o u n d . C a n t h e r e a d e rspo t the d i ff i cu l ty? (The answer appea r s onpage 298. )

    As I ' ve sa id , Exam ple 1 has o f t en beenu s e d t o d e f e n d t h e g o t o s t a t e m e n t . U n -fo r tuna te ly, however, t he example i s to t a l lyunconv inc ing in sp i te o f the a rgum ent s I ' ves t a t e d s o f a r, b e c a u s e t h e m e t h o d i n E x a m p l e1 i s a lmostn e v e r a good way to sea rch anarr ay for x ! Th e fo l lowing modif ica t ion to th ed a t a s t r u c t u r e m a k e s t h e a l g o r i t h m m u c hb e t t e r :

    Example 2:

    A[mq-1] :=x; i := 1;w h i l e A [i] ~ ~c do i := i+ 1 ;i f i > m thenm := i ; B[i] := 1;e l s e B [i ] : = B [ i ] + Ifi;

    E x a m p l e 2 b e a t s E x a m p l e 1 b e c a u s e i tmakes the inne r loop cons ide rab ly f a s t e r. I fw e a s s u m e t h a t t h e p r o g r a m s h a v e b e e nhandc oded in a s sem bly l anguage, so tha t th evalues of i , m, and x are kept in regis ters ,and i f we le t n be the f ina l va lue of i a t theend o f the p rogram, Example 1 wi l l make6n + 10 (+ 3 i f no t found) r e fe rences tomemory fo r da ta and ins t ruc t ions on atyp ica l compute r, wh i l e the second p rogramwill m ake on ly 4n + 14 (+ 6 ' i f no t found) .I f , o n t h e o t h e r h a n d , w e a ss u m e t h a t t h e s e

    - 2 6 7

    p r o g r am s a r e tr a n s l a te d b y a t y p i c a l" 9 0 %eff ic ient compi ler" wi~h bounds-checkingsuppressed , the co r respond ing run- t imef igures a re r e spec t ive ly a b o u t 14n + 5 andl l n + 21. (The append ix to th i s pap e rexpla ins the ground ru les for these ca lcula-t ions . ) Under the f i r s t a s sumpt ion we savea b o u t 3 3 % o f t h e r u n - ti m e , a n d u n d e r t h es e c o n d a s s u m p t i o n w e s a v e a b o u t 2 1 % , s oin bo th cases the e l imina t ion o f the got ohas a l so e l imina ted some o f the runn ingt ime .

    E f f i c i e n c yTh e ra t io o f runn ing t im es ( a bo u t 6 to 4 inthe f i r s t case when n i s la rg e) i s ra th er sur-p r is in g t o p e o p l e w h o h a v e n ' t s t u d i e d p r o -g ram behav io r ca re fu l ly. Example 2 doesn ' tlook tha t much more eff ic ient , but i t i s .Exper i ence has shown ( see [46] , [51 ] ) tha tm o s t o f t h e r u n n i n g t i m e i n n o n - I O - b o u n dp r o g r am s i s c o n c e n t r a t e d i n a b o u t 3 % o f t h esource t ex t . We o f t en see a shor t i nne r loopwhose speed governs the ove ra l l p rogramspeed to a r emarkab le degree ; speed ing up

    t h e i n n e r l o o p b y 1 0 % s p e e d s u p e v e r y t h i n gby a lmos t 10 %. A nd i f t he inne r loop has 10ins truc t ions , a m om ent ' s t ho ug h t wi ll u sua l lycu t i t t o 9 o r f ewer.

    M y o w n p r o g r a m m i n g s t y l e h a s o f c o u rs echanged dur ing the l a s t decade , accord ing tothe t r ends o f the t im es ( e.g. , I 'm no t q u i t e sot r i c k y a n y m o r e , a n d I u s e f e w e r g o t o ' s ) ,b u t t h e m a j o r c h a n g e in m y s t y l e h a s b e e ndue to th i s inne r loop phenomenon . I now

    l o o k w i t h a n e x t r e m e l y j a u n d i c e d e y e a teve ry ope ra t ion in a c r i ti ca l i nne r loop , seek-i n g t o m o d i f y m y p r o g r a m a n d d a t a s t r u c -tu re ( as in the change f rom Exam ple 1 toE x a m p l e 2 ) s o t h a t s o m e o f t h e o p e r a t i o n scan be e l imina ted . The r easons fo r th i s ap -p roach a re tha t : a ) i t doesn ' t t ake long , s incethe inne r loop is shor t ; b ) the payo ff i s r ea l ;and c) I can then afford to be less e ff ic ienti n th e o t h e r p a r t s o f m y p r o g r a m s , w h i c hthe re fo re a re more r eadab le and more eas i lywr i t t en and debugged . Too l s a re be ingdeveloped to make th is c r i t ica l - loop ident i f i -ca t ion job easy ( see fo r exam ple [46] and[ 8 2 ] ) .

    T h u s . i f I h a d n ' t s ee n h o w t o r e m o v e o n eo f t h e o p e r a ti o n s f r o m t h e l o o p in E x a m p l e I

    C o m p u t i n g S u r v e y s,V 6 1 . 6 , N o . 4 , D e . ~ m b e r I ~ 4

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    8/41

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    9/41

    Structured Programming with g o t o Statements

    output for this example, I found that theimprovement in performance was not quiteas much as I had expected.

    Error E xitsFor simplicity I have avoided a very impor-ta nt issue in the previous examples, bu t itmust now be faced. All of the programs wehave considered exhibit bad programmingpractice, since they fail to make the neces-sary check tha t m has not gone out of range.In each case before we perform "m := i" weshould precede that operation by a tes t sucha s

    i f m = m a x t h e n g o t o m e m o r y o v e r f l o w ;

    where max is an appropriate threshold value.I left this statement out of the examplessince it would have been distracting, but weneed to look at it now since it is anotherimportant class of go to statements: aner~vr exit. Such checks on the validity ofdata are very important, especially in soft-ware, and it seems to be the one class of goto's that still is considered ugly but neces-

    sary by today's leading reformers. (I wonderhow Val Schorre has managed to avoid suchgo to 's during all these years.)

    Sometimes it is necessary to exit fromseveral levels of control, cutt ing across codethat may even have been written by otherprogrammers; and the most graceful way todo this is a direct approach with a go to orits equivalent. Then the intermediate levelsof the program can be written under the

    assumption that nothing will go wrong.I will return to the subject of error exitslater.

    Subscript CheckingIn the particular examples given above wecan, of course, avoid test ing m vs. max ifwe have dynamic range-checking on all sub-scripts o f A. But this usually aborts theprogram, giving us little or no control overthe error recovery; so we probably want totest m anyway. And ouch, what subscriptchecking does to the inner loop executiontimes! In Example 2, I will certainly want tosuppress range-checking in the while clausesince its subscript can 't be out of range unless

    2 6 9

    Aim+ 1] was already invalid in the previousline. Similarly, in Example 1 there van be norange error in the for loop unless a rangeerror occurred earlier. I t seems senseless tohave expensive range cheeks in those partsof my programs that I know are clean.

    In this respect I should mention I-Ioare'salmost persuasive arguments to the contrary[40, p. 18]. He points out quite correctly that.the current practice of compiling subscriptrange checks into the machine code while aprogram is being tested, then suppressing thechecks during production runs, is like a sailorwho wears his life preserver while trainingon land but leaves it behind when he sails[

    On the o ther hand, that sailor isn' t so foolishif life vests are extremely expensive, and if heis such an excellent swimmer th at the chanceof needing one is quite small compared withthe other risks he is taking. In the foregoingexamples we typically are much more cer-tain tha t the subscripts will be in range thanthat other aspects of our overall program willwork correctly. John Coeke observes thattime-consuming range checks can be avoided

    by a smart compiler which first compiles thechecks into the program then moves themout of the loop. Wirth [94] and ttoare[39] have pointed out that a well-designedf o r statement can permit even a rathersimple-minded compiler to avoid most rangechecks within loops.

    I believe that range checking should beu s e d f a r m o r e o f t e n t h a n i t c u r r e n t l y is, b u tn o t e v e r y w h e r e . O n t h e o t h e r h a n d I a mr e a l l y a s s u m i n g i nf al li bl e h a r d w a r e w h e n Is a y t h i s ; s u r e l y I w o u l d n ' t w a n t t o r e m o v et h e p a r i t y c h e c k m e c h a n i s m f r o m t h e h a r d -w a r e , e v e n u n d e r a h y p o t h e t i c a l a s s u m p t i o nt h a t i t w a s s l o w i n g d o w n t h e c o m p u t a t i o n .A d d i t i o n a l m e m o r y p r o t e c t i o n i s n e c e s s a r yt o p r e v e n t m y p r o g r a m f r o m h a r m i n g s o m e -o n e e ls e' s, a n d t h e i r s f r o m c l o b b e r i n g m i n e .M y a r g u m e n t s a r e d i r e c t e d t o w a r d s c o m -p i l e d - i n t e s t s , n o t t o w a r d s t h e h a r d w a r em e c h a n i s m s w h i c h a r e r e a l l j ~ n e e d e d t o e n -

    s u r e r e li a bi l it y.

    Hash CodingNow let' s move on to another example, basedon a standard hashing technique but other-

    C o m p u t i n gS u r v ey s , Vo l. 6 , N o . 4 , D e c e m b e r 1 9 7 4

    !

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    10/41

    270 Donald E . Knuth

    wise designed for the same application as theabove. Here h(x) is a hash function whichtakes on values between 1 and m; and x ~ 0.In this case m is somewhat larger than thenumber of items in the table, and "empty"positions are represented by 0.

    E x a m p l e 3 :

    i := h(x);w h i l e A [ i] # 0 d o

    b e g i n i f A [ i ] = x t h e n g o t o f o u n d fi ;i : = i - - 1 ; i f i = 0 t h e n i : = mf i ;

    e n d ;n o t f o u n d : A [i ] : =x; B [ i ] : = 0 ;f o u n d : B [ i] : = B [ i ] + I ;

    If we analyze this as we did Example 1,we see th at the trick which led to Example 2doesn't work any more. Yet if we want toeliminate the go to we can apply the idea ofExample l a by writing

    w h i l e A [ i ] ~ 0a n d h [ i ] ~ x d o . . .

    and by testing afterwards which conditioncaused termination. This version is perhapsa little bit easier to read; unfortunately itmakes a redundant test, which we would liketo avoid if we were in a critical part of theprogram.

    Why should I worry about the redundanttest in this case? After all, the extra testwhether A[i] was ~ 0 or ~ x is being madeoutside of the while loop, and I said beforethat we should generally ecnfine our optimi-zations to inner loops. Here, the reason isthat this while loop won' t usually be a loopat all; with a proper choice of h and m, the

    operation i := i - 1 will tend to be executedvery infrequently, often less than once persearch on the average [54, Section 6.4]. Thus,the entire program of Example 3, except per-haps for the line labeled "not found", mustbe considered as part of the inner loop, ifthis search process is a dominant part of theoverall program (as it often is). The redund-ant test will therefore be significant in thiscase.

    Despite this concern with efficiency, Ishould actually have written the first draftof Example 3 without that go t o statement,probably even using a while clause writtenin an extended language, such as

    w h i l e A [ i ] ~ {0, x } d o . . .

    I

    since this formulation abstracts the realmeaning of what!is happening. Somedaythere may be hardware capable of testingmembership in small sets more efficientlythan if we program the tests sequentially,so tha t such a program would lead ~o bette rcode than Example 3. And there is a muchmore important reason for preferring thisform of the while clause: it reflects a sym-met ry between 0 and x tha t is not present inExample 3. For example, in most softwareapplications it turns out that the conditionA[~] -- x termina tes the loop far more fie-quently than A[~] = 0; with this knowledge,my second draft of the program would bethe following.

    E x a m p l e3 a :

    i :ffi h(x);w h i l e A [ i ] ~ x d o

    b e g i n i f A [ i ] = 0t h e n A [ i ] : = x; B [ i ] : - - 0 ;

    g o t o f o u n d ;fi;i : = i - 1 ; i f i = 0 t h e n i : = r a ft ;

    e n d ;

    found: B[i] :ffi B[i l+I;

    This program is easy to derive from thego to-less form, but not from Example 3;and i t is better tha n Example 3. So, again wesee the advantage of delaying optimizationsuntil we have obtained more knowledge of aprogram's behavior.

    It is instructive to consider Example 3afurther, assuming now that the while loopis performed many times per search. Al-though this should not happen in most ap-plications of hashing, there are other pro-grams in which a loop of the above form ispresent, so it is worth examining what weshould do in such circumstances. If the w h i l eloop becomes an inner loop affecting theoverall program speed, the whole picturechanges; th at redundant test outside the loopbecomes utte rly negligible, but the test"i f i = 0" suddenly looms large. We gen-erally want to avoid testing conditions thatare almost always false, inside a criticalloop. Therefore, under these new assump-tions I would change the data structure byadding a'new element A[0] = 0 to the arr ayand eliminating the test for i ffi 0 as follows.

    Computing Surveys, Vol. 6, No. 4, December 1974

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    11/41

    St ruc tu red Programming wi thg o t o E ~ n t s '271

    Example3b :

    i := h(~);while A[i] ~ xd o

    if A[i] ~ 0t h e n i : = i - 1e l s e i f i = 0t h e n i := m;

    e l s e A[i] := x; B[i] := 0;g o t o found;

    fi ;fi ;

    found: B[ i l := B [ i ]+I ;

    T h e l o o p n o w i s n o t i c e a b l y f a s t e r. A g a i n , Iw o u l d b e u n h a p p y w i t h s l o w s u b s c r ip t r a n g ec h e c k s i f t h is l o o p w e r e c r i t ic a l . I n c i d e n t a l l y,E x a m p l e 3 b w a s d e r iv e d f r o m E x a m p l e 3 a ,a n d a r a t h e r d i f f e re n t p r o g r a m w o u l d h a v ee m e r g e d i f t h e s a m e i d e a h a d b e e n a p p l i e dt o E x a m p l e 3 ; t h e n a t e s t" i f i = 0 " w o u l dh a v e b e e n i n s e r t e doutside t h e l o o p , a t l a b e l" n o t f o u n d " , a n d a n o t h e r g o t o w o u l d h a v eb e e n i n t r o d u c e d b y t h e o p t i m i z a t i o n p r o ce s s.

    A s i n t h e f i r s t e x a m p l e s , t h e p r o g r a m i nE x a m p l e 3 i s f l a w e d i n f a i l i n g t o t e s t f o rm e m o r y o v e r f l o w. I s h o u l d h a v e d o n e t h i s ,f o r e x a m p l e b y k e e p i n g a c o u n t , n , o f h o w

    m a n y i te m s a r e n on z e ro . T h e " n o t f o u n d "r o u t i n e s h o u l d t h e n b e g i n w i t h s o m e t h i n gl ike " n : = n - k l ; i f n = mt h e n g o t om e m o r y o v e r fl o w ".

    Text ScanningT h e f i r s t t i m e I c o n s c i o u s l y a p p l ie d t h e t o p -d o w n s t r u c t u r e d p r o g r a m m i n g m e t h o d o l o g yt o a r e a s o n a b l y c o m p l e x j o b w a s i n t h e l a t es u m m e r o f 19 72 , w h e n I w r o t e a p r o g r a m t op r e p a r e t h e i n d e x t o m y b o o kSort ing andSearching [54 ] . I was qu i t e p l ea sed w i th t hew a y t h a t p r o g r a m t u r n e d o u t ( th e r e w a so n l y o n e s e ri o u s b u g ) , b u t I d i d u s e o n eg o t os t a t e m e n t . I n t h is c a s e t h e r e a s o n w a s s om e -w h a t d i f f e r e n t , h a v i n g n o t h i n g t o d o w i t hex i t i ng f rom loops ; I was ex i t i ng , i n f ac t ,f r o m a n i f - t h e n - e l s e c o n s t r u c t i o n .

    T h e f o l lo w i n g e x a m p l e is a s i m p l if i ed v e r -s i o n o f t h e s i t u a t i o n I e n c o u n t e r e d . S u p p o s ew e a r e p r o c e s s in g a s t r e a m o f t e x t , a n d t h a tw e w a n t t o r e a d a n d p r i n t t h e n e x t c h a r a c t e rf r o m t h e i n p u t ; h o w e v e r , i f t h a t c h a r a c t e r i sa s la sh ( " / " ) w e w a n t t o " t a b u l a t e " i n s t e a d( i . e . , t o a d v a n c e i n t h e o u t p u t t o t h e n e x tt a b - s t o p p o s i t i o n o n t h e c u r r e n t l i n e ) ; h o w -e v e r, t w o c o n s e c u t i v e s l as h e s m e a n s a

    " c a r r i a g e r e t u r n " ( i. e., i to a d v a n c e i nt h eo u t p u t t o t h e b e g i n n i n g o ft h e n e x t l ine) .A f t e r p r i n t i n g a p e r i o d ( " . " ) w e a ls o w a n t t oi n s e r t a n a d d i t io n a l s p a c e in t h e o u t p u t . T h ef o l lo w i n g c o d e c l e a r l y d o e s t h e t r i c k .

    Exam ple 4:

    x :ffi read cha r;if ~ = alasht h e n x := read char;

    i f x = slasht h e n return the carriage;

    g o t o c h a r p r o c e s s e d ;e l s e tabulate;fi;

    fi ;write char (x);i f x = periodt h e n write ch ar (space)fi ;

    char processed:

    A n a b s t r a c t p r o g r a m w i t h s i m i la rc h a r a c -t e r i s t i c s h a s b e e n s t u d i e d b y P e t e r s o n e t a l .[ 77 ; F ig . l ( a ) ] . I n p r ac t i c e we occas iona l l yr u n i n t o s i t u a t i o n s w h e r e a s e q u e n c e o fd e c i s i o n s i s m a d e v i a n e s t e di f - t h e n - e l s e ' s ,a n d t h e n t w o o r m o r e o f t h eb r a n c h e s m e r g ei n t o o n e . W e c a nm a n a g e s u chd e c i s i o n - t a b l et a sk s w i t h o u t g o t o ' s b y c o p y i n g t h e c o m -m o n c o d e i n t o e a c h p l a c e , o r b y d e f i n i n g i ta s a p r o c e d u r e , b u t t h is d o e s n o t s ee m c on -c e p t u a ll y s im p l e r t h a n t o m a k eg o t o a c o m -m o n p a r t o f t h e p r o g r a m i n s u c h c as es . T h u si n E x a m p l e 4 I c o u ld a v o i d t h e g o t o b yc o p y i n g"wri te char (x ) ; f f x ~ pc r /odt h e nwrite char (space)f i " i n t o t h e p r o g r a m a f t e r" tabula te ;" a n d b y m a k i n gc o r r e s p o n d i n gc h a n g e s . B u t t h i s w o u l d b e a p o i n t l e s s w a s t eo f e n e r g y ju s t t o e l im i n a t e a p e r f e c t l y u n d e r -

    s t a n d a b l e g o t o s t a t e m e n t : t h e r e s u l t i n gp r o g r a m w o u l d a c t u a ll yb e h a r d e r t o m a i n -t a i n t h a n t h e f o r m e r , s i n c e t h e a c t i o n o fp r i n t i n g a c h a r a c t e r n o w a p p e a r s i n t w od i f f e r e n t p l a c e s . T h e a l t e r n a t i v e o fd e c l a r i n gp r o c e d u r e s a v o i d s t h e l a t t e r p r o b l e m , b u t i ti s n o t e s p e c i a l l y a t t r a c t i v e e i t h e r. S t i l la n o t h e r a l t e r n a t i v e i s :

    Example4 a:

    x :-- re~td char;double slash := f a l s e ;i f x = slasht h e n x := read char;

    i f x = slasht h e n double slash :ffit r u e ;e l s e tabulate;fi ;

    Com puting Surveys, Vot~ 6, No ..4, Deaem ber-.l~4[ - ,

    - ~ ~ . ~ 4 d ~ . ~ : - " i ~ z : ~ . : ~ . ~ ! "

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    12/41

    272 Donald E. Knuth

    f i ;i f d o u b l e s lasht h e n r e t u r n t he c a r r i a g e ;e l s e w r i t e c h a r ( x ) ;

    i f x = p e r i o d t h e n w r i t e c h a r ( s p a c e ) f i ;fi ;

    I c l a im tha t th i s i s concep tua l ly no s imple rt h a n E x a m p l e 4 ; i n de e d , o n e c a n a rg u e t h a ti t i s ac tua l ly m ore d i ffi cu l t, because i t m akesth e entire r o u t in e a w a r e o f t h e " d o u b l e s l a s h "excep t ion to the ru le s , i n s t ead o f dea l ing w i thi t in one except ional p lace .

    A ConfessionBefore we go on to ano the r example , I m us ta d m i t w h a t m a n y r e a d e r s a l r e a d y s u s p e c t ,n a m e l y, t h a t I ' m s u b j e c t t o s u b s t a n t ia l b i a sbecause I ac tua l ly have a ves t ed in t e res t i ngo to s t a t emen t s ! The s ty le fo r the se r i e so f b o o k s I ' m w r i t i n g w a s s e t i n t h e e a r l y1960s, an d i t wo uld be too d i fficu l t for me tochange i t now; I p resen t a lgor i thms in mybooks us ing in fo rmal Eng l i sh l anguagedesc r ip t ions , and go to o r i t s equ iva len t i sa lmos t the on ly con t ro l s t ruc tu re I have .Wel l , I r a t iona l i ze th i s apparen t anachro -n i sm by a rgu ing tha t : a ) an in fo rmaI Eng l i shdesc r ip t ion seems advan tageous becausem a n y r e a d e r s t e l l m e t h e y a u t o m a t i c a l l yread Eng l i sh , bu t sk ip ove r fo rma l code ; b )w h e n g o t o s t a t e m e n t s a r e u s e d j u d i c i o u s l yt o g e t h e r w i t h c o m m e n t s s t a t i n g n o n o b v i o u sloop inva r i an ts , t he y a re sem an t i ca l ly equ i -v a l e n t t o w h i l e s t a t e m e n t s , e x c e p t t h a tinden ta t ion i s mis s ing to ind ica te the s t ruc -tu re ; c ) the a lgor i thms a re nea r ly a lways

    shor t , so tha t accom pany ing f lowchar t s a reab le to i l l u s t r a t e the s t ruc tu re ; d ) I t ry top resen t a lgor i thms in a fo rm tha t i s mos teff ic ient for imp lem enta t ion , and h igh- levels t ruc tu res o f t en don ' t do th i s ; e ) manyreader s wi ll ge t p l easu re f rom conv er t ing m ysemi fo rmal a lgor i thm s in to be au t i fu l ly s t ruc -tu red p rograms in a fo rma l p rogramminglanguage; and f ) we are s t i l l l earn ing muchabou t con t ro l s t ruc tu res , and I can ' t a ffo rd

    to w ai t for the f ina l consensus.In sp i te of these ra t ional iza t ions , I 'mu n c o m f o r t a b l e a b o u t t h e s i t u a t i o n , b e c a u s eI f ind o thers o ccas ional ly publ ish ing ex-amples o f a lgor i thms in"my" s t y l e b u tw i t h o u t t h e i m p o r t a n t p a r e n t h e s i z e d c o m -m e n t s a n d / o r w i t h u n r e st r a in e d u s e of g ot o

    s t a t eme n t s . In add i t ion , I a l so know places where I l~ave mysel f used a compca ted s t ruc tu re wi th excess ive ly unres t r a ingo to s t a t emen t s , e spec ia l ly the no to r ioAlgor i thm 2 .3 .3A fo r mul t iva r i a t e po lnom ial add i t ion [50]. T he or ig ina l pro grahad a t leas t three bugs ; exerc ise 2 .3 .3-1"Give a fo rma l p roof (o r d i sp roof ) o f thv a l i d i t y o f A l g o r i t h m A " , w a s t h e r e f ou n e x p e c t e d l y e a s y. N o w i n t h e s e c o n d e dt ion , I be l i eve tha t the r ev i sed a lgor ithm cor rec t, bu t I s t il l do n ' t kno w an y good wto p rove i t ; I ' ve had to r a i se the d i ff i cu lra t ing of exerc ise 2 .3 .3-14, and I ho pe somd a y t o s e e t h e a l g o r it h m c l ea n e d u p w i t h oloss of i ts eff iciency.

    M y books emph as ize e ff ic i ency becauthey dea l wi th a lgor i thms tha t a re used rpea te d ly a s bu i ld ing b locks in a l a rge va r i eo f app l ica t ions . I t i s im por tan t to keeeff ic iency in i t s p lace , as men t ioned abo vbu t w hen e ffi c iency coun t s w e shou ld a lk n o w h o w t o a c h i e ve i t.

    In o rde r to make i t poss ib le to de r ivquan t i t a t ive a s sessmen t s o f e ff i c i ency, m

    b o o k s s h o w h o w t o a n a l y z e m a c h i n e l aguage p rograms ; and these p rograms aexpressed in MIXAL, a symbol i c a s semblanguage tha t exp l i c i t ly co r responds onfo r-one to m ach ine l anguage . T h i s has iuses , but there i s a danger of p lac ing tomuch s t r e s s on a s sembly code . P rograms MIXAL a re l ike p rogram s in ma ch ine l aguage , devo id o f s t ruc tu re ; o r, more p rc ise ly, i t i s d i ff icu l t for our eyes to perce i

    t h e p r o g r a m s t r u c tu r e . A c c o m p a n y i n g c oment s exp la in the p rogram and re l a t e i t t he g loba l s t ruc tu re i l lu s t r a t ed in f lowcharb u t i t i s n o t s o e a s y t o u n d e r s t a n d w h a t go ing on ; and i t i s easy to make mis t akep a r t l y b e c a u s e w e re l y s o m u c h o n c o m m e nwhich m igh t po ss ib ly be inaccura te desc rit ions o f wh a t the p rog ram rea l ly does. I t c l ea r ly be t t e r to wr i t e p rograms in a l aguage tha t r evea l s the con t ro l s t ruc tu reven i f we a re in t ima te ly consc ious o f tha rdware a t each s t ep ; and the re fo re I wbe d i scuss ing a s t ruc tu red a s sem bly l anguac al le d P L / M I X i n t h e fi ft h v o l u m e o fTheart of computer programming. Such a l anguage(ana logous to W ir th ' s PL 360 [95] ) shour e a l l y b e s u p p o r t e d b y e a c h m a n u f a c t u r

    Comput ingSurveys, Vol. 6, No. 4, December 1974

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    13/41

    Structured Programming with g o t o Statenwnt,,~ 273

    for each machine in place of the old-fash-ioned structureless assemblers that still pro-liferate.

    On the other hand I'm not really un-happy that MIxAL programs appear in mybooks, because I believe that MIXAL is agood example of a "quick and dirty assem-bler", a genre of software which will alwaysbe useful in its proper role. Such an assembleris characterized by language restrictionsthat make simple one-pass assembly possible,and it has several noteworthy advantageswhen we are first preparing programs for anew machine: a) it is a great improvementover numeric machine code; b) its rules are

    easy to state; and c) it can be implementedin an afternoon or so, thus getting an effi-cient assembler working quickly on whatmay be very primitive equipment. So far Ihave implemented six such assemblers, atdifferent times in my life, for machines orinterpretive systems or microprocessors th athad no existing software of comparableutility; and in each case other constraintsmade it impractical for me to take the extra

    time necessary to develop a good, structuredassembler. Thus I am sure that the conceptof quick-and-dirty-assembler is useful, andI' m glad to let MIXAL illustrate wha t one islike. However, I also believe strongly thatsuch languages should never be improved tothe point where they are too easy or toopleasant to use; one must restrict their useto primitive facilities that are easy to imple-ment efficiently. I would never switch to atwo-pass process, or add complex pseudo-operations, macro-facilities, or even fancyerror diagnostics to such a language, norwould I maintain or distribute such alanguage as a standard programming tool fora real machine. All such ameliorations andrefinements should appear in a structuredassembler. Now tha t the technology isavailable, we can condone unstructuredlanguages only as a bootstrap-like means toa limited end, when there are strong eco-nomic reasons for not implementing a bettersystem.

    Tree SearchingBut, I'm digressing from my subject of go t oelimination in higher level languages. A few

    weeks ago I decided to choose an algorithmat random from my books, to study its useof go to statements. The very first exampleI encountered [54, Algorithm 6.2.3C] turnedout to be another case where existing pro-gramming languages have no good substitu tefor go to's. In simplified form, the loopwhere the trouble arises can be written asfollows.

    E x a m p l e 5 :

    c o m p a r e :i f A [ i ] < xt h e n i f L [ i ] # 0

    t h e n i := L [ i ] ; g o t o c o m p a re ;e l s e L [ i ] : = j ; g o t o i n se r tfi;

    e l s e i f R [ i ] # 0t h e n i : = R [ i ] ; g o t o c o m p a r e ;e l s e R [ i ] : - - j ; g o t o i n s e r tf i ;

    fi;insert: A[j] := x ;L[j] := 0; R[j] := 01j := j+l;

    This is part of the well-known "tree searchand insertion" scheme, where a binary searchtree is being represented by three arrays:A[i] denotes the information stored at node

    number i, and L[i], R[~] are the respectivenode numbers for the roots of that node'sleft and right subtrees; emp ty subtrees arerepresented by zero. The program searchesdown the tree until finding an empty sub-tree where x can be inserted; and variable jpoints to an appropriate place to do theinsertion. For convenience, I have assumedin this example that x is not already presentin the search tree.

    Example 5 has four go to statements, butthe control structure is saved from obscuritybecause the program is so beautifully sym-metric between L and R. I h-low that thesego to statements can be eliminated byintroducing a Boolean variable which be-comes true when L[i] or R[i] is found to bezero. But I don't want to test this variablein the inner loop of my program.

    Systematic EliminationA good deal of theoretical work has beenaddressed to the question of g o t o elimina-tion, and I shall now try to summarize thefindings and to discuss their relevance.

    S. C. Kleene proved a famous theorem in1956 [48] which says, in essence, that the set

    Com putin g Surveys, Vol. 6, N o. 4, Dec em ber 1974

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    14/41

    274 Donald E. Knuth

    of all paths through any flowchart can berepresented as a "regular expression" Rbuilt up from the following operations:

    8

    R 1 ; R2

    R 1 O R2R+

    t h e s i n g l e a r cs of the flowchartc o n c a t e n a t i o n ( al l p a t h sconsistingof a path of R~ followed by a p a t ho f R~)union (all paths of either R~ or R2)iteration (all paths of the form p~;p2; "" ; p~ for some n )_ 1,w h e r e each p~ is a path of R)

    These regular expressions correspondloosely to programs consisting of statementsin a programming language related by thethree operations of sequential composition,conditionals (if-then-else), and iterations(while loops). Thus, we might expect thatthese three program control structures wouldbe sufficient for all programs. However,closer analysis shows that Kleene's theoremdoes not relate directly to control structures;the problem is only superficially similar. Hisresult is suggestive but not really applicablein this case.

    The analogous result for control struc-tures was first proved by G. Jacopini in 1966,in a paper written jointly with C. BShm[8]. Jacopini showed, in effect, that anyprogram given, say, in flowchart form can betransformed systematically into anotherprogram, which computes the same resultsand which is built up from statements in theoriginal program using only the three basicoperations of composition, conditional, anditeration, plus possible assignment state-

    meat s and tests on auxiliary variables. Thus,in principle, go to statements can always beremoved. A detailed exposition of Jacopini'sconstruction has been given by H. D. Mills[69].

    Recent interest in structured programminghas caused many authors to cite Jacopini'sresult as a significant break through and as acornerstone of modern programming tech-nique. Unfortunately, these authors are un-

    aware of the comments made by Cooper in1967 [16] and later by Bruno and Steiglitz[10], namely, that from a practical stand-point the theorem is meaningless. Indeed,any program can obviously be put into the"beautifully structured" form

    p : - - 1 ;w h i l e p > 0 d o

    b e g i n i f p = 1 t h e n p e r f o rm s t e p 1;p : = s u c c e s s o r o f s t e p 1 fi ;

    i f p = 2 t h e n p e r f o r m s t e p 2;p : = s u c c e s s o r s t e p 2fi;

    . . .i f p = nn t h e n p e r f o r m s t e p n ;

    p : = s u c c e s s o r o f s t e p n f i;e n d .

    Here the auxiliary variable p serves as aprogram counter representing which box ofthe flowchart we're in, and the program stopswhen p is set to zero. We have eliminated allg o to's , but we've actua lly lost all the struc-ture.

    Jacopini conjectured in his paper thatauxiliary variables are necessary in general,and that the go to's in a program of theform

    L l : i f B i t h e n g o t oL 2 f i ;$1 ;

    i f B ~ t h e n g o t o L ~ fi;S ~ ;

    g o t o L 1 ;L~: S,;

    cannot always be removed unless additionalcomputa tion is done. Floyd and I proved thisconjecture with John Hopcroft's help [52].Sharper results were later obtained by Ash-croft and Man na [1], Bruno and Steiglitz[10], Kosara ju [57], and Peterson, Kasami,and Tokura [77].

    Jaeopini's original construction was notmerely the trivial flowchart emulationscheme indicated above; he was able tosalvage much of the given flowchart struc-ture if it was reasonably well-behaved. Amore general technique of g o t o elimination,devised by Ashcroft and Manna [1], madeit possible to capture still more of a givenprogram's natural flow; for example, theirtechnique applied to Example 5 yields

    Example 5a:

    t : = t r u e ;w h i l e t d o

    b e g i n i f A [ i ] < xt h e n i f L [ i ] # 0 t h e n i : = L [ i ] ;e l s e L [ i ] : = j ; t : = f a l s e f i;

    e l s e i f R [ i ] # 0 t h e n i : = R [ i ] ;e l s e R [ i ] : = j ; t : = f a l s e f i ;

    e n d ;AUI := x;

    C o m p u t i n g S u r v e y s , Vo l . 6 , N o . 4 , D e c e m b e r 1 9 74

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    15/41

    Structured Programming with g o t o Statements 275

    B u t , i n g e n e r a l , t h e i r t e c h n i q u e m a y c a u s e ap r o g r a m t o g r o w e x p o n e n t i a l l y i n s iz e ; a n dw h e n e r r o r e x i t s o r o t h e r r e c a l c i t r a n t g ot o ' s a r e p r e s e n t , t h e r e s u l t i n g p r o g r a m s w i l li n d e e d l o o k r a t h e r l ik e t h e f l o w c h a r t e m u l a -t o r s k e t c h e d a b o v e.

    I f s u c h a u t o m a t i c g o t o e l i m i n a t i o np r o c e d u r e s a r e a p p l i e d t o b a d l y s t r u c t u r e dp r o g r a m s , w e c a n e x p e c t t h e r e s u l t i n g p r o -g r a m s t o b e a t l e a s t a s b a d l y s t r u c t u r e d .D i j k s t r a p o i n t e d t h i s o u t a l r e a d y in [2 3],s a y i n g :

    The exercise to translate an arbitrary flowdiagram more or less mechanically into ajumpless one, however, is not to be recom-mended. T hen the resul ting f low diagramcannot be expected to be more transparentthan the original one.

    I n o t h e r w o r d s , w e s h o u l d n ' t m e r e l yr e m o v e g o t o s t a t e m e n t s b e c a u s e i t ' s t h ef a s h i o n a b l e t h i n g t o d o ; t h e p r e s en c e o ra b s e n c e o f g o t o s t a t e m e n t s i s n o t r e a l ly th eis su e . T h e u n d e r l y i n g s t r u c t u r e o f t h ep r o g r a m i s w h a t c o u n t s , a n d w e w a n t o n l yt o a v o i d u s a g e s w h i c h s o m e h o w c l u t t e r u p

    t h e p r o g r a m . G o o d s t r u c t u r e c a n b e e x p re s s e din FORTRAN or COBOL, or ev en in ass em blyl a n g u a g e , a l t h o u g h l e s s c l e a r l y a n d w i t hm u c h m o r e t r o u b l e . T h e r e a l g o a l i s t of o r m u l a t e o u r p r o g r a m s i n s u c h a w a y t h a tt h e y a r e e a s i l y u n d e r s t o o d .

    P r o g r a m s t r u c t u r e r e f e r s t o t h e w a y i nw h i c h a c o m p l e x a l g o r i t h m is b u i l t u p f r o msuccess ive ly s imp le r p roces ses . In mos ts i t u a t i o n s t h i s s t r u c t u r e c a n b e d e s c r i b e d

    v e r y n i c e l y i n t e r m s o f s e q u e n t i a l c o m p o s i -t i on , cond i t i ona l s , s imp le i t e r a t ions , andw i t h c a s e s t a t e m e n t s f or m u l t i w a y b r a n c h e s;u n d i sc i p li n e d g o t o s t a t e m e n t s m a k e p r o -g r a m s t r u c t u r e h a r d e r t o p e r c e i v e , a n d t h e ya r e o f t e n s y m p t o m s o f a p o o r c o n c e p t u a lf o r m u l a t i o n . B u t t h e r e h a s b e e n f a r t o om u c h e m p h a s i s o n g o t o e l im i n a t io n in s t e a do f o n t h e r e a l l y i m p o r t a n t i s s u e s ; p e o p l eh a v e a n a t u r a l t e n d e n c y t o s e t u p a l l e a s i lyu n d e r s t o o d q u a n t i t a t i v e g o a l l i k e t h e a b o l i -t i o n o f j u m p s , i n s t e a d o f w o r k i n g d i r e c t l yf o r a q u a l i t a t i v e g o a l l i k e g o o d p r o g r a ms t r u c t u r e . I n a s i m i l a r w a y, m a n y p e o p l eh a v e s e t u p " z e r o p o p u l a t i o n g r o w t h " a s ag o a l t o b e a c h i e v e d , w h e n t h e y r e a l l y d e s i r e

    l iv i n g c o n d i ti o n s t h a t a r e m u c h h a r d e r t oq u a n t i f y.

    P r o b a b l y t h e w o r s t m i s t a k e a n y o n e c a nm a k e w i t h r e s p e c t t o t h e s u b j e c t o fg o t os t a t e m e n t s is t o a s s u m e th a t " s t r u c t u r e d -p r o g r a m m i n g " i s a c h i e v e d b y w r i t i n g p r o -g r a m s a s w e a l w a y s h a v e a n d t h e n e l i m i -n a t i n g t h e g o t o ' s . M o s t g o t o ' s s h o u l d n ' tb e t h e r e i n t h e f i rs t p l a c e ! W h a t w e r e a l l yw a n t is t o c o n c e iv e o f o u r p r o g r a m i n s u c ha w a y t h a t w e r a r e ly e v e nthink a b o u t g o t os t a t e m e n t s , b e c a u s e t h e r e a l n e e d f o r t h e mh a r d l y e v e r a r is e s. T h e l a n g u a g e in w h i c h w eexpres s ou r i deas has a s t rong in f luence ono u r t h o u g h t p r o c e s s e s . T h e r e f o r e , D i j k s t r a

    [ 2 3 ] a s k s f o r m o r e n e w l a n g u a g e f e a t u r e s - -s t r u c tu r e s w h i c h e n c o u ra g e c l ea r t h i n k i n g - -i n o rd e r t o a v o i d t h e g o t o ' s t e m p t a t i o n s t o -w a r d c o m p l i c a t i o n s .

    E v e n t I n d i c o t o r sT h e b e s t s u c h la n g u a g e f e a tu r e I k n o w h a sr e c e n t l y b e e n p r op o s e d b y C . T. Z a h n[102] . S ince th i s i s s t i l l i n t he expe r imen ta ls t a g e, I w i ll t a k e t h e l i b e r t y o f m o d i f y i n g

    h is " s y n t a c t i c s u g a r " s li g h tl y, w i t h o u tc h a n g i n g h i s b a si c i d e a . T h e e s s e n t ia l n o v e l t yi n h i s a p p r o a c h i s t o i n t r o d u c e a n e w q u a n -t i t y i n t o p r o g r a m m i n g la n g u a g es , c a l le d a nevent indicator ( n o t t o b e c o n f u s e d w i t hc o n c e p t s f r o m P L / I o r S IM S C ~IP T). M yc u r r e n t p r e f e r e n c e i s t o w r i t e h i s e v e n t -d r i v e n c o n s t r u c t i n t h e f o ll o w i n g t w o g e n e r a lf o r m s .

    A) l o o p u n t i l ( e v e n t h o r - . - o r {e v e n t )s :(statem ent l ist)0;

    r e p e a t ;t h e n (event)l = > (statem ent list)l;

    (event)~ = >( s t a t e m e n t l i s t ) n ;fi;

    B ) b e g i n u n t i l ( e v e n t )l o r . . . o r ( ev e n t) n ;(statem ent l ist)0;

    e n d ;t h e n ( e v e n t ) t = > ( s t a t e m e n t l is t ) t ;

    ievent)~ = > (sta tem en t list)z;fi :

    T h e r e i s a ls o a n e w s t a t e m e n t , " ( e v e n t ) " ,w h i c h m e a n s t h a t t h e d e s i g n a t e d e v e n t h a so c c u r r e d : s u c h a s t a t e m e n t i s a l l o w e d o n l y

    Com puting Surveys, VoL 6, No. 4 , Decem ber 1974

    i

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    16/41

    276 Donald E. Knuth

    within (statement lisQ0 of an u n t i l con-struct which declares that event.

    In form (A), (statement list)0 is executedrepeatedly until control leaves the construct entirely or until one of the named eventsoccurs; in the latter case, the statementlist corresponding to that event is executed.The behavior in form (B) is similar, exceptthat no iteration is implied; one of the namedevents must have occurred before the e n dis reached. The th e n . . , fi part may beomitted when there is only one event name.

    The above rules should become clearafter looking at what happens when Example5 above is recoded in terms of this new fea-

    ture:E x a m p l e 5 b :

    l o o p u n t i ll e f t l e a f h i to rr i g h t l e a f h i t :

    i f A [ i] < xt h e n i f L [ i] # 0 t h e n i : = L [ i ];

    e l s e left leaf hit fi;e l s e i f R [ i ] # 0 t h e n i : = R [ i ];

    e l s e r i g h t l e a f h i t f i ;fi;

    r e p e a t ;t h e n l e f t l e a f h i t = > L [ i ] : = j;

    right leaf hit = > R[i] := j;fi;A[j] := x; L[j] := 0; R[j] := 0; j := j+ l ;

    Alternatively, using a sing leevent,

    Example 5c:

    l o o p u n t i l leaf replaced:i f A [ i ] < xt h e n i f L [ i] # 0 t h e n i : = L [ i ]

    e l s e L[i] := j; leaf replaced fi;e l s e i f R [ i ] # 0 t h e n i : = R [ i]

    e l s e R[i] := j; leaf replaced fi;fi;

    r e p e a t ;A [ j ] : = x ; L [ j ] : ~ O ; R [ j ] : = O ; j : = j + l ;

    For reasons to be discussed later, Example5b is preferable to 5c.

    It is importan t to emphasize that the firstline of the construct merely declares theevent indicator names, and that eventindicators are not conditions which are beingtested continually; (event) statements aresimply transfers of control which the com-piler can treat very efficiently. Thus, inExample 5e the statement "leaf replaced"is essentially a go to which jumps out ofthe loop.

    This use of events is, in fact, semanticallyequivalent to a restricted form of go t ostatement, which Peter Landin discussedin 1965 [58] before most of us were ready tolisten. Landin's device has been reformula tedby Clint and Hoare [14] in the followingway: Labels are declared at the beginningof each block, just as procedures normallyare, and each label also has a (label body)just as a procedure has a (procedure body).Within the block whose heading containssuch a declaration of label L, the statementgo to L according to this scheme means"execute the body of L, then leave theblock". It is easy to see that this is exactly

    the form of control provided by Zahn'sevent mechanism, with the (label body)sreplaced by (statement list)s in the t h e n fi postlude and with (event) statementscorresponding to Landin's go to. Thus,Clint and Hoare would have written Ex-ample 5b as follows.

    w h i l e t r u e d ob e g i n l a b e ll e f t l e a f h i t ; L [ i ] : = j ;

    l a b e l r i g h t l e a f h i t ; R [ i ] : = j ;

    i f A [ i ] < xt h e n i f L [ i ] # 0 t h e n i : = L[i];e l s e g o t oleft leaf hit fi;

    e l s e i f R [ / ] # 0t h e n i : = R [ / ] ;e l s e g o t or i g h t l e a f h i t f i ;

    e n d ;A [ j ] : = x ; L [ j ] : = 0 ; R [ j ] : = 0 ; j : = j + l ;

    I believe the program reads much better inZahn's form, with the (label body)s set inthe code between that which logicallyprecedes and follows.

    Landin also allowed his "labels" to haveparameters like any other procedures; thisis a valuable extension to Zahn's proposal,so I shall use events with value parametersin several of the examples below.

    As Zahn [102] has shown, event-drivenstatements blend well with the ideas ofstructured programming by stepwise refine-ment. Thus, Examples 1 to 3 can all be castinto the following more abstr act form, using

    an event "f ound " with an integer parameter:b e g i n u n t i lf o u n d :

    s e a r c h t a b l e f o r xan di n s e r t i t i f n o t p r e s e n t ;

    e n d ;t h e n f ou n d ( i n t e g e r j)= > B [ j] : = B [ j ] + I ;fi;

    Com puting Su~eys, VoL 6, No. 4, Decem ber 1974

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    17/41

    S t r u c t u r e d P r o g r a m m i n g w i t hg o t o S t a ~ m c n t o

    T h i s m u c h o f t h e p r o g r a m c a n b e w r i t t e nb e f o r e w e h a v e d e c i d e d h o w t o m a i n t a i nt h e t a b l e . A t t h e n e x t l e v e l o f a b s t r a c t i o n ,w e m i g h t d e c i d e t o r e p r e s e n t t h e t a b l e a s as e q u e n t i a l l i st , as i n E x a m p l e 1, s o t h a t

    '277

    i f x = slasht h e n double s l a sh ;e l s e tabu/ate;

    n o r m a lc h a r a c t e r i n p u t(x);fi;

    e l s e n o r m a l c h a r a c t e r i n p u t ( x ) ;

    " s e a r c h t a b l e . . . " w o u l d e x p a n d i n t of o r i : = 1 s t e p 1 u n t i l m d o

    i f A[ i] = x th en found( i ) f i;m := m ~- l ; Aim] := x ; found(m) ;

    N o t e t h a t t h i s f o r l o o p i s m o r e d i s ci p li n e dt h a n t h e o n e in o u r o ri g in a l E x a m p l e 1,b e c a u s e t h e i t e r a t i o n v a r i a b l e i s n o t u s e do u t s i d e t h e l o o p ; it n o w c o n f o r m s t o t h e r u l e so f A L GO L W a n d A L G O L 6 8. S u c h f o r l o o p sp r o v i d e c o n v e n i e n t d o c u m e n t a t i o n a n da v o i d c o m m o n e r r o r s a s s o c i a t e d w i t h g l o b a lv a r i ab l e s ; t h e ir a d v a n t a g e s h a v e b e e nd i s c u s s e d b y H o a r e [ 3 9 ] .

    S i m i l a r l y, if w e w a n t t o u s e t h e i d e a o fE x a m p l e 2 w e m i g h t w r i t e t h e f o l l o w i n gc o d e a s t h e r e f i n e m e n t o f " s e a r c h t a b l e . . " "

    b e g i n i n t e g e r i ;A[m-b l ] := x ; i := 1 ;whi le A[i ] ~ xd o i := i -b l ;i f i > m t h e n m :=i ; B [ m ] : = 0 f i ;fou nd (/) ;e n d ;

    A n d f i n a ll y, if w e d e c i d e t o u s e h a s h i n g ,w e o b t a i n t h e e q u i v a l en t o f E x a m p l e 33w h i c h m i g h t b e w r i t t e n a s fo ll ow s .

    fi )e n d ;t h e n n o r m a l c h a ra c te r i n p u t ( c h a rx) ffi >

    w r i t e c h a r ( x ) ;i f x ---p e r i o d t h e n w r i t e c h a r ( s p a c e ) fi;

    double s lash = >r e t u r n t h e c a r r i a g e ,fi;

    T h i s p r o g r a m s t a t e s t h e d e s i r e d a c t i o n s ab i t m o r e c l e ar ly t h a n a n y o f o u r p r e v i o u sa t t e m p t s w e r e a b l e t o d o .

    E v e n t i n d ic a to r s , h a n d l e e r r o r e x i t s to o .

    F o r e x a m p l e , w e m i g h t w r i t e a p r o g r a m a sf o l l o w s .

    b e g i n u n t i l e rr or o r n o r m a l e n d:

    i f m = m a x t h e n e rr or ( ' s y m b o l ta b l efull ' ) f i ;

    normal end ;e n d ;t h e n e r ro r ( s t r i n g E ) ffi

    pr in t ( 'un recoverab le e r ro r, ' ; E ) ;normal end = >

    p r i n t ( 'c o m p u t a t io n c o m p l e t e ' ) ;fi;

    Comp arison of FeaturesO f c o ur s e, e v e n t in d i c a t o r s a r e n o t t h e o n l yd e c e n t a l t e r n a t i v e s t Og o t o s t a t e m e n t s

    b e g i n i n t e g e r i ;i := h(x);l o o p u n t i l p r e se n t o rabsen t :

    i f A[i ] = x th en p resen t f i;i f A[i] = 0 th en absen t fi ;i : = i - 1 ;i f i = 0 t h e n i := m f i ;

    r e p e a t ;t h e n presen t = > found( i ) ;

    absen t = > A[ i] := x ; found( / ) ;fi;

    e n d ;

    t h a t h a v e b e en p ro p o s ed . M a n y a u t h o r sh a v e s u g g e s t e d l a n g u a g e f e a t u r e s w h i c hp r o v i d e r o u g h l y e q u i v a l e n t f a c il it ie s , b u tw h i c h a r e e x p r e s s e d in t e r m s o fe x i t , j u m p -o u t , b r e a k , o r l e a v es t a t e m e n t s . K o s a r a j u

    [57] h a s p r o v e d t h a t s u c h s t a t e m e n t s a r es u f f i c i e n t t o e x p r e s s a l l p r o g r a m s w i t h o u tg o t o ' s a n d w i t h o u t a n y e x t r a c o m p u t a t io n ,b u t o n l y i f a n e x i t f r o m a r b i t r a r i l y m a n yl e v e ls o f c o n t r o l i s p e r m i t t e d .

    T h e e a r li e s t l a n g u a g e f e a t u r e s o f t h i s k i n dT h e b e g i n u n t i l ( e ve n t) co n s t r u ct uls o

    p r o v i d e s a n a t u r a l w a y t o d e a l w i t h d e c i si o n-t a b l e c o n s t r u c t i o n s s u c h a s t h e t e x t - s c a n n i n ga p p l i c a t i o n w e h a v e d i s cu s s ed .

    E x a m p l e 4 b :b e g i n u n t i lnormal charac te r inpu t

    o r double s lash:c h a r x ;x := read char;i f x = s l a s ht h e n x := r ead char~~

    ( b e s i d e s L a n d i n ' s p r o p o s a l ) p r o v i d e d e s s e n -t i a l l y o n l y o n e e x i t f r o m a l o o p ; t h i s m e a n st h a t t h e c od e ap p e a r in g i n t h e t h e n . . . f ip o s t l u d e o f o u r e x a m p l e s w o u l d b e i n s e r t e d

    i n t o t h e b o d y i t s el f b e f o r e b r a n c h i n g . ( S e eE x a m p l e 5 c .) T h e s e p a r a t i o n o f s u c h c o d ea s i n Z a h n ' s p r o p o s a l is b e t t e r , m a i n l yb e c a u s e t h e b o d y o f th e c o n s t r u c t c o rr e-s p o n d s t o c o d e t h a t i s w r i t t e n u n d e r d i f f e r e n t" i n v a r i a n t a s s u m p t i o n s " w h i c h a r e i n o p e r a -t i v e a f t e r a p a r t i c u l a r e v e n t h a s o c c u r r e d .

    Com puting Surveys, V ol. 6, N o. 4, December 1~4

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    18/41

    278 D o n a ld E . K n u t h

    Thus, each'event corresponds to a par ticularset of assertions about the state of theprogram, and the code which follows thatevent takes cognizance of these assertions,which are ra ther different from the assertionsin the main body of the construct. (For thisreason I prefer Example 5b to Example 5c.)

    Language features allowing multiple exitshave been proposed by G. V. Bochmann [7],and independently by Shigo et al. [86]. Theseare semantically equivalent to Zahn's pro-posals, with minor variations; but theyexpress such semantics in terms of state-ments that say "exit to (label)". I believeZahn's idea of event indicators is an im-

    provement on the previous schemes, becausethe specification of events instead of labelsencourages a better conception of the pro-gram. The identifier given to a label is oftenan imperative verb like "insert" or "com-pare", saying what action is to be done next,while the appropriate identifier for an eventis more likely to be an adjective like "found" .The names of .events are very much like thenames of Boolean variables, and I believe

    this accounts for the popularity of Booleanvariables as documentation aids, in spite ofthei r inefficiency.

    Putting this another way, it is muchbetter from a psychological standpoint tow r i t e

    loo p unt l l fou nd ; fou nd; r e p e a t

    than to write

    s e a r c h : w h i l e t r u e d ob e g i n . . . ; l e a v e s e a r c h ; . - . e n d .

    The l e a v e o r e x i tstatement is operationallythe same, but intuitively different, since ittalks more about the program than aboutthe problem.

    The PL/I language allows programmer-defined ON-conditions, which are similarin spirit to event indicators. A programmerfirst executesa statement " O N CONDITION(identifier) block" which specifies a block

    of code that is to be executed when theidentified event occurs, and an occurrenceof that event is indicated by writing SIG-NAL CONDITION (identifier). However,the analogy is not very close, since controlreturns to the statement following theSIGNAL statement after execution of the

    specified block of code, and the block maybe dynamically respecified.

    Some people have suggested to me thatevents should be called "conditions" instead,by analogy with Boolean expressions. How-ever, th at terminology would tend to imply arelation which is continually being moni-tored, instead of a happening. By writing"loop unt i l y p r i m e is near y : . . . " we seemto be saying that the machine should keeptrack of whether or not y and y p r i m e arenearly equal; a better choice of words wouldbe an event name like "loop until con-vergence established:.-." so that we canwrite " i f a b s ( y p r i m e - y ) < e ps il o n X yt h e n convergence established". An eventoccurs when the program has discoveredthat the state of computatioD has changed.

    Simple IterationsSo far I haven't mentioned what I believeis really the most common situation in whichgo to statements are needed by an ALGOLor PL/I programmer, namely a simpleiterative loop with one entrance and one

    exit. The iteration statements most oftenproposed as alternatives to go to statementshave been "while B do S" and "repeat Su n t i l B". However, in practice, the itera-tions I encounter very often have the form

    A: S;i f B t h e n g o t o Zfi;T ; g o t o A ;

    Z :

    where S and T both represent reasonably

    long sequences of code. If S is empty, wehave a while loop, and if T is empty wehave a repeat loop, but in the general caseit is a nuisance to avoid the go to state-ments.

    A typical example of such an iterationoccurs when S is the code to acquire orgenerate a new piece of data, B is the testfor end of data, and T is the processing ofthat data. Another example is when the code

    preceding the loop sets initial conditionsfor some iterative process; then S is a com-putation of quantities involved in the testfor convergence, B is the test for conver-gence, and T is the adjustment of variablesfor the next iteration.

    Dijkstra [29] apt ly named this a loop

    C o m p u t i n g S u r ve y s, Vo l . 6 , N o . 4 , D e c e m b e r 1 9 7 4

  • 8/8/2019 Knuth - 1974 - Structured Programming With Go to Statements

    19/41

    Structured Programming with g o t o Sta tements 279

    w h i c h i s p e r f o r m e d"n and a ha l f t imes" .The usua l p rac t i ce fo r avo id ing go to ' s i nsuch loops i s e i the r to dup l i ca te the codefor S , wr i t ing

    S; w h i l e B d o b e g i nT; S e n d ;whe re B i s the n ega t ion o f re l a t ion B ; o r tof igu re ou t some so r t o f " inve r se" fo r T sot h a t "T-i; T" i s equ iva len t to a nu l l s t a t e -men t , and wr i t ing

    T-l; r e p e a t T; S u n t i l B;

    o r t o d u p l i c a te t h e c o d e f o r B a n d t o m a k e aredundan t t e s t , wr i t ing

    r e p e a t S; if B t h e n T fi; u n t i l B;

    or i t s equ iva len t . The r eade r who s tud iesgo to - l e s s p rograms as they appea r in thel i te ra ture wi l l f ind tha t a l l three of thesera the r unsa t i s f ac to ry cons t ruc t ions a re usedf requen t ly.

    I d iscussed th is we akne ss of ALGOL in al e t t e r to Nik laus Wir th in 1967 , and heproposed two so lu t ions to the p rob lem,t o g e t h e r w i t h m a n y o t h e r i n s t r u c t i v e i d e a s

    in an unpub l i shed repor t on bas ic concep t so f p rogram m ing l anguages [94] . H i s f i rs tsugges t ion was to wr i t e

    r e p e a t b e g i n S ; w h e n B e xi t ; T; en d ;

    and reade r s who remember 1967 wi l l a l soapprec ia te h is second sugges t ion ,t u r n o n b e g i n S ; w h e n B dr o p o u t ; T ; e n d .

    Nei the r se t o f de l imi te r s was f e l t t o bequ i t e r igh t , bu t a modi f i ca t ion o f the f i r s tproposal (a l lowing one or more s ingle- levele x i t s t a t e m e n t s w i t h i n r e p e a t b e g i n . . .e n d ) was la t e r incorp ora ted in to an exper i-m en ta l ve r s ion o f the ALGOL W language .O t h e r l a n gu a g e s s u c h a s B C P L a n d B L IS Si n c o r p o r a t e d a n d e x t e n d e d t h e e x i t i d e a , a smen t ioned above . Zahn ' s cons t ruc t ion nowal lows us to wr i te , for example ,

    l o o p u n t i lall data exhausted:S;if B the n all data exhausted fi;T ;

    r e p e a t ;

    and th i s i s a be t t e r syn tax fo r the n +p r o b l e m t h a n w e h a v e h a d p r e v i o u s l y.

    On the o the r hand , i t wou ld be n ices t i f

    ou r l anguage wou ld p rov ide a s ing le f ea tu rewhich covered a l l s imple i t e ra t ions wi thou tgo ing to a r a the r "b ig" cons t ruc t l i ke thee v e n t - d r i v e n s c h e m e . W h e n a p r o g r a m m e ru s e s t h e s im p l e r f e a t u r e h e i s th e r e b y m a k i n g

    i t c l ea r tha t he has a s imple i t e ra t ion , wi thexac t ly one cond i t ion which i s