Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

c - Legitimate uses of a goto


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

While you can use goto in this way, it's generally considered bad style since the language has other constructs like while that do the same thing in a "cleaner" fashion.

Once place where it does make sense to use goto is to jump forward for error handling situations. For example, this:

void foo()
{
    char *p1 = NULL, *p2 = NULL, *p3 = NULL, *p4 = NULL;
    
    p1 = malloc(1000);
    if (!p1) {
        perror("malloc failed");
        return;
    }
    p2 = malloc(1000);
    if (!p2) {
        perror("malloc failed");
        free(p1);
        return;
    }
    p3 = malloc(1000);
    if (!p3) {
        perror("malloc failed");
        free(p2);
        free(p1);
        return;
    }
    p4 = malloc(1000);
    if (!p4) {
        perror("malloc failed");
        free(p3);
        free(p2);
        free(p1);
        return;
    }

    // Do something with p1, p2, p3, p4

    free(p4);
    free(p3);
    free(p2);
    free(p1);
}

Can be translated to this:

void foo()
{
    char *p1 = NULL, *p2 = NULL, *p3 = NULL, *p4 = NULL;
    
    p1 = malloc(1000);
    if (!p1) {
        perror("malloc failed");
        goto err0;
    }
    p2 = malloc(1000);
    if (!p2) {
        perror("malloc failed");
        goto err1;
    }
    p3 = malloc(1000);
    if (!p3) {
        perror("malloc failed");
        goto err2;
    }
    p4 = malloc(1000);
    if (!p4) {
        perror("malloc failed");
        goto err3;
    }

    // Do something with p1, p2, p3, p4

    free(p4);
err3:
    free(p3);
err2:
    free(p2);
err1:
    free(p1);
err0:
    return;
}

This puts all of the cleanup code in one place.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...