home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / cplus / 13269 < prev    next >
Encoding:
Text File  |  1992-09-03  |  2.2 KB  |  70 lines

  1. Path: sparky!uunet!haven.umd.edu!darwin.sura.net!wupost!micro-heart-of-gold.mit.edu!uw-beaver!news.u.washington.edu!sumax!thebes!manutius!garyp
  2. From: garyp@manutius.UUCP (Gary Powell)
  3. Newsgroups: comp.lang.c++
  4. Subject: Legal uses of goto
  5. Message-ID: <667@manutius.UUCP>
  6. Date: 3 Sep 92 14:56:37 GMT
  7. Reply-To: garyp@manutius.UUCP (Gary Powell)
  8. Distribution: na
  9. Organization: Aldus Corporation, Seattle WA
  10. Lines: 58
  11.  
  12. IMHO Besides optimizing critical loops there is one other area where
  13. goto's are useful, add clarity, and ease maintiance.  Error trapping.
  14. Until I get a fully implemented try,catch scheme I plan on using goto's to avoid
  15. over nesting when I check the state of the result of a function and wish
  16. to exit the fn on an error condition. These goto's only go forward and only
  17. with the express intention of cleaning up and returning from the fn.
  18.  
  19. This is my concession to having only one return in a fn, being religious about
  20. checking the return state of a fn, and not wishing to read the guts of the
  21. fn in a 30 character column on the right side of the page. Note, I try to use
  22. descriptive labels so a casual reader understands where and why the goto is
  23. being used.
  24.  
  25. eg:
  26. --------------------------------------------
  27. // Sample code
  28.  
  29. enum iResult { OK, ERROR};
  30. extern iResult gn(char *&);
  31. extern iResult hn(char *&);
  32.  
  33. iResult fn(int *arg)
  34. {
  35.     iResult result = OK;
  36.     char *g;
  37.     char *h;
  38.  
  39.     if ( arg == 0 )
  40.     {
  41.     result = ERROR;
  42.     goto Exit;
  43.     }
  44.  
  45.     result = gn(g);  // Some other routine which allocates memory.
  46.     if ( result == 0)
  47.     goto Exit;
  48.  
  49.     result = hn(h);  // Some other routine which allocates memory.
  50.     if ( result == 0)
  51.     goto Free_gn;
  52.  
  53.     // More routines called each allocating memory or doing some
  54.     // other task which requires cleanup before the fn returns.
  55.     // If you do this 20 times in a fn the indentation and nested {}'s
  56.     // make it almost unreadable without the goto's.
  57.  
  58.     delete h;
  59. Free_gn:
  60.     delete g;
  61. Exit:
  62.     return (iResult);
  63. }
  64.  
  65.  
  66. Gary Powell ------------+ Internet:     garyp@aldus.com
  67. c/o Aldus Corporation   | uunet:        manutius!garyp@uunet.uu.net
  68. 411 1st Ave South       | uucp:         camco!manutius!garyp
  69. Seattle, WA 98104  USA  | Voice:        (206) 622-5500
  70.