Goto

From C

Jump to: navigation, search

It's not uncommon for C beginners to be under the false assumption that it's always wrong to use goto statements. Although it is possible to misuse goto statements, there are cases where goto statements are very much useful. A sensible guideline as to when it's appropriate to use a goto statement would be- whenever the alternative makes your code more complex or less readable.

Cleaning up

The following snippet of code is an example for how goto statements can be useful for cleaning up. Also see: http://www.iso-9899.info/wiki/Cleanup

int func(void) {
    void *p1 = malloc(10);
    if (p1 == NULL)
        goto error1;
    
    void *p2 = malloc(10);
    if (p1 == NULL)
        goto error2;
    
    /* do something */
    
    return 0;
    
    error2:
    free(p1);
    
    error1:
    return -1;
}

Breaking out a nested loop

The following snippet of code is an example for breaking out a nested loop using a goto statement.

int func(char *s) {
    for (int i = 0; i < 10; i++) {
        for (int y = 0; y < 5; y++) {
            /* do something */
            
            if (error)
                goto breakout;
        }
    }
    
    return 0;
    
    breakout:
    return -1;
}

.

Personal tools