Path: csiph.com!newsfeed.hal-mli.net!feeder3.hal-mli.net!newsfeed.hal-mli.net!feeder1.hal-mli.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: James Kuyper Newsgroups: comp.lang.c Subject: Re: Redundant return() Date: Tue, 15 May 2012 18:39:44 -0400 Organization: A noiseless patient Spider Lines: 54 Message-ID: <4FB2DB30.30109@verizon.net> References: <27375124.1151.1337067212163.JavaMail.geo-discussion-forums@vbip22> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 7bit Injection-Info: mx04.eternal-september.org; posting-host="2P71cupDoazVVolqpw1jrw"; logging-data="7777"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19wKfSYF6T9fZzkaumAqd4PB87V3bMEFAA=" User-Agent: Mozilla/5.0 (X11; Linux i686; rv:9.0) Gecko/20111220 Thunderbird/9.0 In-Reply-To: Cancel-Lock: sha1:hV31J0OkUHNSzcHNHERFjqrxmM0= Xref: csiph.com comp.lang.c:20837 On 05/15/2012 06:24 PM, Ian Collins wrote: > On 05/16/12 09:58 AM, BartC wrote: >> "James Kuyper" wrote in message >> news:jotj8p$2j5$1@dont-email.me... ... >>> The relevant issue isn't speed, but ease of comprehension. Supporters of >>> "single exit" claim it's easier to comprehend; my personal experience is >>> that early-return is easier. >> >> Yes. Easier in that there is then a choice. >> >> I can't see the problem with multiple returns. No matter how many returns >> there are in one function, the next statement executed will always be the >> one falling the original call. That's not much different from 'single exit'. > > Clean-up is always the elephant in the room with multiple returns in C. > Hence the proliferation of goto spaghetti. I for one prefer early > return on precondition tests, but once a function allocates a resource > or changes a state, there should only be one. I'm in perfect agreement here. If I allocate memory, I normally use the following structure where possible (there's obviously situations in which it's NOT possible): retval = SUCCESS; p = malloc(count * sizeof *p); if (p == NULL) { // error handling return ERROR1; } else { // Normal processing. 'return' prohibited in this block. if(error condition) { // other error handling retval = ERROR2; } free(p); } return retval; I handle fopen() and fclose() similarly, and any other similar book-end functions (the libraries I use have quite a few book-end pairs). This approach doesn't scale well when many different resources need to be managed simultaneously, in which case more complicated approaches are needed.