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

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

    It never occurred to me to use goto or do { } while(0) for error handling in this way - its pretty neat, however after thinking about it I realised that in many cases I can do the same thing by splitting the function out into two:

    int Foo(void)
    {
        // Initialise things that may need to be cleaned up here.
        char* somePtr = malloc(1024);
        if (somePtr = NULL)
        {
            return NULL;
        }
    
        if (FooInner(somePtr) < 0)
        {
            // Something went wrong so clean-up.
            free(somePtr);
            return NULL;
        }
    
        return somePtr;
    }
    
    int FooInner(char* somePtr)
    {
        if (something(somePtr) < 0) return -1;
        if (somethingElse(somePtr) < 0) return -1;
        // etc
    
        // if you get here everything's ok.
        return 0;
    }
    

    This does now mean that you get an extra function, but my preference is for many short functions anyway.

    After Philips advice I've also decided to avoid using control flow macros as well - its clear enough what is going on as long as you put them on one line.

    At the very least Its reassuring to know that I'm not just missing something - everyone else has this problem too! :-)

提交回复
热议问题