Good Uses of Goto in C or C
Despite the often-held view that goto is universally harmful, there are certain circumstances where its use can provide clear benefits.
Cleanup Blocks
One such case is in the creation of cleanup blocks, a pattern commonly used in C to ensure proper resource deallocation in the event of errors. Using goto, we can implement a cleanup block as follows:
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 code allows for clear and efficient handling of error conditions. In the event of an error in doB() or doC(), the appropriate cleanup functions are called, and execution proceeds to the exit label to return from the function.
Specific Unconditional Branching
Goto can also be beneficial when performing specific unconditional branching. For example, the following code simulates an infinite loop using goto:
infinite_loop: // code goes here goto infinite_loop;
This approach is more specific and self-documenting than using a while loop with a degenerate condition, as it clearly indicates the intent to continue looping.
Cautions
It is important to note that goto should not be used indiscriminately. It can easily lead to spaghetti code if not used judiciously. However, when used appropriately, it can provide a valuable tool for creating efficient and readable code.
The above is the detailed content of When is Using `goto` in C or C Acceptable?. For more information, please follow other related articles on the PHP Chinese website!