Legitimate use case: error cleanup blocks
What you'll learn: How to use the goto statement responsibly to centralize resource cleanup and avoid "arrow code" nesting.
The problem: The "Cleanup Staircase"
In C, you often have to manually acquire resources, like opening files or allocating memory. If you need three different resources to complete a task, you have to check if each one succeeded. This often leads to "staircase" code:
void process_data() {
FILE *f = fopen("data.txt", "r");
if (f) {
int *buf = malloc(1024);
if (buf) {
if (do_something(f, buf)) {
// Success!
}
free(buf); // Cleanup 1
}
fclose(f); // Cleanup 2
}
}
As you add more resources, your code drifts further to the right, and you find yourself repeating cleanup logic in multiple if branches. It becomes a nightmare to maintain.
The solution: Jumping to the end
While goto is often discouraged because it can create "spaghetti code," the C community widely accepts one specific pattern: the error cleanup block.
Instead of nesting if statements, you handle errors by jumping to a single labeled section at the bottom of the function. This section unwinds the resources in reverse order.
A concrete example
Think of this like an assembly line. if any station fails, you don't keep moving down the line; you hit the "Abort" button and go straight to the cleaning crew at the exit.
int save_report(const char *filename) {
int status = 0; // 0 for failure, 1 for success
FILE *f = fopen(filename, "w");
if (!f) goto cleanup;
int *data = malloc(1000 * sizeof(int));
if (!data) goto cleanup;
// Perform operations
fprintf(f, "Report Data...");
status = 1; // If we reached here, everything worked!
cleanup:
// This code runs whether we succeeded or failed
if (data) free(data);
if (f) fclose(f);
return status;
}
Why this is better
- Linear Flow: Your main logic stays at the left margin instead of being buried in nested blocks.
- Single Point of Exit: You have one place to look for cleanup logic, reducing the chance of memory leaks.
- Readability: It is immediately clear to other programmers that
goto cleanupmeans "something went wrong; get us out of here safely."
Key takeaway
Use goto to jump forward to a unified cleanup block at the end of a function to keep your error handling clean and leak-free.