home *** CD-ROM | disk | FTP | other *** search
- 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
- From: garyp@manutius.UUCP (Gary Powell)
- Newsgroups: comp.lang.c++
- Subject: Legal uses of goto
- Message-ID: <667@manutius.UUCP>
- Date: 3 Sep 92 14:56:37 GMT
- Reply-To: garyp@manutius.UUCP (Gary Powell)
- Distribution: na
- Organization: Aldus Corporation, Seattle WA
- Lines: 58
-
- IMHO Besides optimizing critical loops there is one other area where
- goto's are useful, add clarity, and ease maintiance. Error trapping.
- Until I get a fully implemented try,catch scheme I plan on using goto's to avoid
- over nesting when I check the state of the result of a function and wish
- to exit the fn on an error condition. These goto's only go forward and only
- with the express intention of cleaning up and returning from the fn.
-
- This is my concession to having only one return in a fn, being religious about
- checking the return state of a fn, and not wishing to read the guts of the
- fn in a 30 character column on the right side of the page. Note, I try to use
- descriptive labels so a casual reader understands where and why the goto is
- being used.
-
- eg:
- --------------------------------------------
- // Sample code
-
- enum iResult { OK, ERROR};
- extern iResult gn(char *&);
- extern iResult hn(char *&);
-
- iResult fn(int *arg)
- {
- iResult result = OK;
- char *g;
- char *h;
-
- if ( arg == 0 )
- {
- result = ERROR;
- goto Exit;
- }
-
- result = gn(g); // Some other routine which allocates memory.
- if ( result == 0)
- goto Exit;
-
- result = hn(h); // Some other routine which allocates memory.
- if ( result == 0)
- goto Free_gn;
-
- // More routines called each allocating memory or doing some
- // other task which requires cleanup before the fn returns.
- // If you do this 20 times in a fn the indentation and nested {}'s
- // make it almost unreadable without the goto's.
-
- delete h;
- Free_gn:
- delete g;
- Exit:
- return (iResult);
- }
-
-
- Gary Powell ------------+ Internet: garyp@aldus.com
- c/o Aldus Corporation | uunet: manutius!garyp@uunet.uu.net
- 411 1st Ave South | uucp: camco!manutius!garyp
- Seattle, WA 98104 USA | Voice: (206) 622-5500
-