You don't need to use assert on pointers at all. The idea is to ensure that you don't work when dereferencing pointers when they are null.
You can do this with assert , but this is not a very professional way of handling such errors, since it invariably terminates the program - it is not a good idea if the user has not saved, for example, his last three hours of data entry.
What you have to do with pointers is check them for errors and grace. In other words, your function returns some kind of error or does nothing (not everyone will agree with this approach, but it is quite acceptable if it is documented).
The assert material is, in my opinion, meant to detect problems during development, so you will find that assert does nothing to build releases under some compilers. This does not replace defensive programming.
How to do it:
#include <assert.h> void doSomethingWithPointer (int *p) { assert (p != 0); cout << *p << endl; }
but it’s better to do it like:
void doSomethingWithPointer (int *p) { if (p != 0) cout << *p << endl; }
In other words, even if your “contract” (API) states that you are not allowed to get pointers to zero, you should still handle them gracefully. Old quote: be conservative in what you give, liberal in what you accept (rephrase).
source share