Quote:Original post by Gage64
Do you think the use of goto is justified here?
Not really. Lots of C programmers would use goto to handle this kind of thing, but they'd also generally structure it rather differently. :)
Quote:If not, how would you rewrite the code to avoid it?
/* NOTE: ONLY func() gets mentioned in the header file. Unless you have a good reason otherwise. :) */void func_mem_file(int* arr, FILE* file) { if (some error) { return; } /* ... */ if (some error) { return; } /* ... */ if (some error) { return; } /* ... */}void func_mem(int* arr) { FILE *file = fopen("myfile.txt", "t"); if (file) { func_mem_file(arr, file); } else { printf("Failed to open file"); } fclose(file); /* this could instead go in the if-clause above. */}void func() { int *arr = (int*)malloc(sizeof(int) * 50); if (arr) { func_mem(arr); } else { printf("Error allocating memory"); } free(arr); /* this could instead go in the if-clause above. */}
Quote:Original post by AcidZombie24
I love gotos, i just never have a chance to use it :( (thats good tho)
...
The other time i use goto is
Wait, what?
@abeylin: free()ing NULL is fine, just like delete'ing NULL.
Quote:Original post by thedustbustr
Linux: Using goto In Kernel Code
Heh. IMX, people who defend goto in those sorts of threads generally don't know what they're talking about, and it's generally pretty transparent (at least to me) that this is the case. The last post shown, in particular, is gold:
Quote:
No, it is gross and it bloats the kernel. It inlines a bunch of junkfor N error paths, as opposed to having the exit code once at the end. Cache footprint is key and you just killed it.Nor is it easier to read.As a final argument, it does not let us cleanly do the usual stack-esquewind and unwind, i.e. do A if (error) goto out_a; do B if (error) goto out_b; do C if (error) goto out_c; goto out; out_c: undo C out_b: undo B: out_a: undo A out: return ret;Now stop this. Robert Love
Er, you don't get "stack-esque wind and unwind" by calling one function from another (as in my above snippet)? Where does he think he got the term from?! He must be imagining (this is the only explanation I can think of) that every user of the code calls the allocation function, then the implementation function, then the cleanup function afterward. Not very imaginative, hmm?
Further, my technique offers the usual benefits of function decomposition: namely, (a) you can (in some cases; i.e. if your available resource set is a prefix of the total required set, in the order you choose to put them) reuse resources from other places if you happen to have them for some reason (and want to hang onto them afterwards, as you typically would in these cases); and (b) you can ignore the resource allocation code
completely while debugging the implementation function.
Although I suppose it's bad form to speak ill of the dead (the thread, not the poster!)...
[Edited by - Zahlman on July 3, 2008 2:56:24 PM]