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

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

    Besides goto, standard C has another construct to handle exceptional flow control setjmp/longjmp. It has the advantage that you can break out of multiply nested control statements more easily than with break as was proposed by someone, and in addition to what goto provides has a status indication that can encode the reason for what went wrong.

    Another issue is just the syntax of your construct. It is not a good idea to use a control statement that can inadvertibly be added to. In your case

    if (bla) NOT_ERROR(X);
    else printf("wow!\n");
    

    would go fundamentally wrong. I'd use something like

    #define NOT_ERROR(X)          \
      if ((X) >= 0) { (void)0; }  \
      else return -1
    

    instead.

提交回复
热议问题