Home > Backend Development > C++ > When Is `goto` Actually Beneficial in C and C ?

When Is `goto` Actually Beneficial in C and C ?

Susan Sarandon
Release: 2024-12-13 03:10:11
Original
544 people have browsed it

When Is `goto` Actually Beneficial in C and C  ?

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;
Copy after login

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;
}
Copy after login

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:

  • Avoid knee-jerk reactions and assume the validity of well-crafted goto statements.
  • Focus on technical merits, excluding subjective personal preferences.
  • Recognize that loop constructs and braces can be used in conjunction with goto where necessary.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template