Checking for null before pointer usage

后端 未结 13 2396
孤独总比滥情好
孤独总比滥情好 2021-02-20 09:32

Most people use pointers like this...

if ( p != NULL ) {
  DoWhateverWithP();
}

However, if the pointer is null for whatever reason, the functi

13条回答
  •  没有蜡笔的小新
    2021-02-20 09:53

    Well the answer to the first question is: you are talking about ideal situation, most of the code that I see which uses if ( p != NULL ) are legacy. Also suppose, you want to return an evaluator, and then call the evaluator with the data, but say there is no evaluator for that data, its make logical sense to return NULL and check for NULL before calling the evaluator.

    The answer to the second question is, it depends on the situation, like the delete checks for the NULL pointer, whereas lots of other function don't. Sometimes, if you test the pointer inside the function, then you might have to test it in lots of functions like:

    ABC(p);
    a = DEF(p);
    d = GHI(a);
    JKL(p, d);
    

    but this code would be much better:

    if(p)
    {
     ABC(p);
     a = DEF(p);
     d = GHI(a);
     JKL(p, d);
    }
    

提交回复
热议问题