TIP: Click on subject to list as thread! ANSI
echo: c_echo
to: John H. Guillory
from: Pascal Schmidt
date: 2004-05-03 01:14:26
subject: Merits

Hi John! :-)

 JHG>     fp = fopen("foo","w");
 JHG>     if (fp != NULL) {
 JHG>        res = write(fp, ...);
 JHG>        if (res != -1) {
 JHG>          res = write(fp, ...);
 JHG>        }
 JHG>      }
 JHG>      fclose(fp);
My problem with that style is that the indentation doesn't suggest that the
normal expected flow of operations is fopen, write, write, then fclose.
Instead, the non-error-case code ends up being shifted more and more to the
right.

 JHG> is more along the lines of how to do it, though in the above, it 
 JHG> looks more like your wanting to do C++ try/catch statements...
Yes, that kind of construct would be helpful, especially when doing several
I/O operations in a row. I wouldn't want all the rest of C++, though. ;)

 JHG> And what's wrong with:

 JHG> void CleanUp(FILE *fp) {
 JHG>      fclose(fp);
 JHG> }
I would make that function inline to remove the overhead. No need to create
a stack frame and a copy of fp for the argument.

 JHG> and adding 1 line that reads CleanUp(fp);  after closing if?
I'd get a problem of finding suitable names once I need more than one of
those. CleanUp1, CleanUp2, ... no, I wouldn't want that.

In one of my projects I have a function that ends like this:

out_new:
        free(new);
out_db:
        sysdb_close(db, 0);
out_tar:
        tar_close(fp);
out:
        return res;

Each of the labels is jumped to from more than one error situation,
depending on what needs to be undone at that point. I do agree one can
write cleanup and error handling code in a structured way, I just don't
think it is necessarily clearer.

One can write unreadable and unmaintainable code both ways.

Ciao
Pascal

--- Msged/LNX 6.1.1
* Origin: let fun a b c d = b (c,d) in a op < 17 end 23 (1:153/401.2)
SEEN-BY: 633/267 270
@PATH: 153/401 307 140/1 106/2000 633/267

SOURCE: echomail via fidonet.ozzmosis.com

Email questions or comments to sysop@ipingthereforeiam.com
All parts of this website painstakingly hand-crafted in the U.S.A.!
IPTIA BBS/MUD/Terminal/Game Server List, © 2025 IPTIA Consulting™.