c++visual-c++assert

Use of Assert and NULL pointer validation what's better to use


While doing programming I am using assert as well as NULL pointer validation.

But as I know assert will be useful only in DEBUG mode.

My question is: If I have an internal pointer which I am sure can't be NULL.

For example if a function fun returns a pointer, I can use assert

test* ptr = fun(); // return a pointer of type test
assert(ptr);

//do some operation

or NULL pointer validation

test* ptr = fun(); // return a pointer of type test
assert(ptr);
if (NULL != ptr) {
    //do some operation
}

Which coding practice is better?

I tend to think second option is better because I have situations when the value of ptr returns NULL in abnormal cases that we can't think of.


Solution

  • The real solution depends on the semantic of the function fun.

    If returning NULL is semantically invalid, then I think fun should throw an appropriate exception (such as std::logic_error1) instead of returning NULL, and you could use assert on the call site to ensure that fun is working fine, and if it is not working fine, then abort the program. In this way, the bug in fun doesn't propagate to the rest of the program, as it is caught immediately.

    However, if returning NULL from fun is semantically valid, then you should check the return value on the call-site using if and assert is not really needed in this case, because you will use if anyway.

    1. Or you could use std::runtime_error or std::domain_error.