Take the 2-minute tour ×

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)

    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.

share|improve this question
C or C++? The best-practices of each language are wildy different...case in point, goto has very little use in C++ (I'd argue none), while in C it's a pretty standard way of jumping to cleanup code, as you see in your post. –  GManNickG Dec 4 '12 at 23:43

2 Answers 2

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?

share|improve this answer

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.

share|improve this answer

Your Answer


