Is there a better way to do C style error handling?

前端 未结 10 1700
时光说笑
时光说笑 2021-02-20 06:43

I\'m trying to learn C by writing a simple parser / compiler. So far its been a very enlightening experience, however coming from a strong background in C# I\'m having some pro

10条回答
  •  别那么骄傲
    2021-02-20 07:34

    One technique for cleanup is to use an while loop that will never actually iterate. It gives you goto without using goto.

    #define NOT_ERROR(x) if ((x) < 0) break;
    #define NOT_NULL(x) if ((x) == NULL) break;
    
    // Initialise things that may need to be cleaned up here.
    char* somePtr = NULL;
    
    do
    {
        NOT_NULL(somePtr = malloc(1024));
        NOT_ERROR(something(somePtr));
        NOT_ERROR(somethingElse(somePtr));
        // etc
    
        // if you get here everything's ok.
        return somePtr;
    }
    while (0);
    
    // Something went wrong so clean-up.
    free(somePtr);
    return NULL;
    

    You lose a level of indentation though.

    Edit: I'd like to add that I've nothing against goto, it's just that for the use-case of the questioner he doesn't really need it. There are cases where using goto beats the pants off any other method, but this isn't one of them.

提交回复
热议问题