Why should I use asserts?

后端 未结 19 2008
遇见更好的自我
遇见更好的自我 2020-12-12 13:47

I never got the idea of asserts -- why should you ever use them?

I mean, let\'s say I were a formula driver and all the asserts were things like security belt, helm

19条回答
  •  一整个雨季
    2020-12-12 14:18

    Because they make debugging easier.

    The time consuming part of debugging is tracing a problem from the symptom you first notice back to the error in the code. Well written assertions will make the symptom you notice much closer to the actual code problem.

    A very simple example would be a bug where you index past the end of an array and cause memory corruption which eventually causes a crash. It can take a long time to trace back from the crash to the offending index operation. However, if you have an assertion next to that index operation that checks your index, then your program will fail right next to the error, so you'll be able to find the problem quickly.

提交回复
热议问题