ASSERT(pointer);
pointer->x;
In this code, the ASSERT seems to be redundant. If the pointer is NULL, pointer->x will fail anyway. Is my argument correct?
The important (if not main) purpose of assertions is to document the invariants that are supposed to hold at certain point in the code. The fact that assert
can also abort the program if the invariant is broken is just icing on the cake, albeit a very useful one. I'd say that in a typical program 90% of assertions are assertions that rather obviously can't fail and never will fail. In other words, assert
is to a large degree a kind of formalized comment language. Formalized in a sense that these "comments" are written in the same language the rest of the code is written in (C/C++), as opposed to plain English.
In your code sample the assertion is there to tell you that the pointer is not supposed to be null here. That's why it is there. In that sense this assert
is not redundant.
As far as the execution flow is concerned, assert
is always redundant, which is why assertions are typically not compiled in the release version of the code. There's nothing to prevent you from keeping the assertions in release code as well, but normally it is done by introducing a special kind of "release assertion". In any case, making the main functionality of the code depend in the actions taken by an assertion is not a good programming practice. Assertions are supposed to be redundant, as far as the main functionality of the code is concerned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With