Examples of Beneficial Goto Implementations in C and C
Despite the widespread disapproval towards goto statements, there are instances where it can be employed effectively. This thread explores such cases, inspired by an upvoted answer that was initially perceived as a joke.
Case Study: Infinite Loop
The following example demonstrates a specific and documented use of goto:
infinite_loop: // code goes here goto infinite_loop;
This loop is preferable to alternatives due to its clarity and specificity. Goto represents an unconditional branch, while its alternatives rely on structures with conditional branches and degenerate always-true conditions. Moreover, the label documents the intent, eliminating the need for additional comments.
Case Study: Cleanup in C
In C, a common use of goto is for branching to a cleanup block:
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 concise and structured error handling. Each potential error condition is handled with a goto statement that branches to the appropriate cleanup code. RAII in C provides a more idiomatic way to handle such scenarios.
Criteria for Evaluation
To ensure a fair assessment, the following criteria have been established:
The above is the detailed content of When Is `goto` Actually Beneficial in C and C ?. For more information, please follow other related articles on the PHP Chinese website!