Reputation: 20076
I've been writing code for an open source project BRL-CAD, a respectable project in development for over 30 years now. While modifying a file i noticed some strange logic, in particular the use of goto as a means of exiting the function when an error arises. Every book i have read preaches the fact that every goto has a better replacement, but in this case i agree with the source that a goto would be the best possible option. Given:
tables.c is a large file that contains 3 functions used in the program to sort and get data tables. Below is a snippet of code that checks for an error and hits the goto if an error is encountered, entire file: http://pastebin.com/u4jnNbLu
if ((tabptr=fopen(argv[1], "w+")) == NULL) { //takes place 300-400 lines before the end goto is declared
bu_vls_printf(gedp->ged_result_str, "%s: Can't open %s\n", argv[0], argv[1]);
status = GED_ERROR;
goto end;}
goto end:
end: //frees memory used in function and returns the status(which became an error above)
bu_vls_free(&cmd);
bu_vls_free(&tmp_vls);
bu_ptbl_free(&cur_path);
return status;
Is the use of goto as a function abort ok? I've never thought about goto like that before, but it seems more logical to me than placing the code in a nest of confusing braces and while's / if's / else's that constantly butt in the code to check if something is wrong.
Upvotes: 0
Views: 742
Reputation: 46913
This is a common construct in pure C (and some C++ that uses return values instead of exceptions for errors), and is, IMO, perfectly acceptable. This keeps all of the cleanup in one place (or as close to one place as is possible based on the structure of the function) and is much, much easier to read and maintain than a tangled web of nested ifs to validate that everything worked correctly.
Upvotes: 4
Reputation: 25552
goto have a bad reputation but that does not mean it should not be used. I've been using goto for years in C to handle specific error cases.
You can find in the Coding Style of the Linux Kernel that goto are used too for theses cases : http://www.kernel.org/doc/Documentation/CodingStyle
You can find a discussion about the use of goto in C here : GOTO still considered harmful?
Upvotes: 3