Home >Backend Development >C++ >When Is `goto` Useful in C or C for Cleanup?
Good Uses of Goto in C or C
Contrary to the assertion of "Goto Considered Harmful," the goto statement still holds value in certain programming scenarios. This question explores examples of effective goto usage in C or C .
Cleanup Blocks
One notable use case for goto is for handling cleanup blocks in C. When multiple operations must be performed in sequence, and any failure requires a controlled cleanup of the previous operations, the goto statement provides a concise and explicit way to handle this:
void foo() { if (!doA()) goto exit; if (!doB()) goto cleanupA; if (!doC()) goto cleanupB; /* everything has succeeded */ return; cleanupB: undoB(); cleanupA: undoA(); exit: return; }
This approach allows for a clear and structured handling of error scenarios and ensures that any necessary cleanup operations are executed before exiting the function.
The above is the detailed content of When Is `goto` Useful in C or C for Cleanup?. For more information, please follow other related articles on the PHP Chinese website!