When should we use asserts in C?

前端 未结 9 1764
孤街浪徒
孤街浪徒 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:01

    Here's a real-world example of an assertion I wrote yesterday.

    I had two parallel arrays -- let's call them a and b -- and I was about to run an index i from 0 up to the size of a, and then do something with a[i] and b[i]. But if there were fewer elements in b than in a, my code would have an array bounds violation on b. But other parts of the code are supposed to keep the sizes of a and b identical. So I put an assertion before the loop, asserting that the sizes of a and b were equal.

    The sizes should be equal -- but if somehow they're not, I want the code to fail on the assertion that tells me why, rather than failing strangely on the Undefined Behavior that would result when I tried to read beyond the end of array b, if it were smaller.

提交回复
热议问题