Re: Goto still considered helpful
- From: Ed Jensen <ejensen@xxxxxxxx>
- Date: Mon, 15 Oct 2007 17:09:19 -0000
Peter Pichler <usenet@xxxxxxxxxxxxx> wrote:
[SNIP: Examples]
Which one is more readable?
I actually found your version a little tricky to read. I find
functions more readable if all the clean up happens in one place.
It took me a few seconds to make sure your files were properly closed
no matter what series of events happened.
Using your approach, things would get more tricky pretty quickly if
more resources were added to the function, such as dynamically
allocated read and write buffers.
Also, your approach unnecessarily duplicates code. Even your simple
example contains multiple calls to close the very same file.
I like the following pattern, which keeps the resource clean up in one
place, and the pattern scales well if more resources are added to the
function in the future:
int fcopy(char const *dst, char const *src)
{
FILE *sf = NULL;
FILE *df = NULL;
sf = fopen(src, "r");
if (!sf)
goto done;
df = fopen(dst, "w");
if (!df)
goto done;
/* copy happens here */
done:
if (sf)
fclose(sf);
if (df)
fclose(df);
return /* value indicating success or failure */ 0;
}
.
- Follow-Ups:
- Re: Goto still considered helpful
- From: ¬a\\/b
- Re: Goto still considered helpful
- From: Peter Pichler
- Re: Goto still considered helpful
- References:
- Goto still considered helpful
- From: James Dow Allen
- Re: Goto still considered helpful
- From: Army1987
- Re: Goto still considered helpful
- From: Malcolm McLean
- Re: Goto still considered helpful
- From: Kenneth Brody
- Re: Goto still considered helpful
- From: Peter Pichler
- Goto still considered helpful
- Prev by Date: Re: Increment/decrement question
- Next by Date: Re: About the typecasting to the LHS
- Previous by thread: Re: Goto still considered helpful
- Next by thread: Re: Goto still considered helpful
- Index(es):
Relevant Pages
|
Loading