maybe I shouldn't be using "assert" everywhere
Closed this issue · 1 comments
It is not OK to do this substitution. The second example is wrong, because assert(x) gets expanded to nothing in non-debug builds (when NDEBUG is defined). This implies that the pointer checks in assert above are removed from the code in release builds. That is definitely wrong.
So, when should one use assert? It is useful for documenting and debugging. In a way, you're saying, "I am sure that this condition is true, and am putting it here as an assert to catch bad code during debugging, and to document the condition to the readers of the code".
So, there is a BIG difference between the two examples. For things like checking the return value of malloc, assert is wrong because there is no guarantee that they will return non-NULL, and as I have mentioned above, assert(x) means "I am completely sure x is true", and not just "If x is not true, it is bad". For this, one uses if(x) good(); else bad(); control.