When should we use asserts in C?

前端 未结 9 1732
孤街浪徒
孤街浪徒 2020-12-02 11:21

I am writing a function in C. As a matter of style, when is it good to use assert compared to returning an error code. Lets say the function is dividing two numbers. Should

9条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 12:13

    First, assert from the header can be disabled (e.g. by compiling with gcc -DNDEBUG), and sometimes is disabled for the "production" version of a binary.

    Second, as stated by Linux man page,

       The  purpose  of  this macro is to help the programmer find bugs in his
       program.   The  message  "assertion  failed  in  file  foo.c,  function
       do_bar(), line 1287" is of no help at all to a user.
    

    So assert should fail only in buggy situations. In exceptional or error situations, you should do something else.

    Some tools (or even compilers) might use assert-ions to e.g. optimize your code.

    In your example of a quotient function, you'll use assert if, inside your entire program, you are sure that the divisor should be non-zero (but then it could make sense to name the function differently, perhaps quotient_by_non_zero). If you consider that it could happen, make it a fatal message, an exception (i.e. longjmp in C), an error code, etc.

提交回复
热议问题