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

前端 未结 10 1842
时光说笑
时光说笑 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:28

    THis must be thought on at least two levels: how your functions interact, and what you do when it breaks.

    Most large C frameworks I see always return a status and "return" values by reference (this is the case of the WinAPI and of many C Mac OS APIs). You want to return a bool?

    StatusCode FooBar(int a, int b, int c, bool* output);
    

    You want to return a pointer?

    StatusCode FooBar(int a, int b, int c, char** output);
    

    Well, you get the idea.

    On the calling function's side, the pattern I see the most often is to use a goto statement that points to a cleanup label:

        if (statusCode < 0) goto error;
    
        /* snip */
        return everythingWentWell;
    
    error:
        cleanupResources();
        return somethingWentWrong;
    

提交回复
热议问题