Checking for null before pointer usage

后端 未结 13 2397
孤独总比滥情好
孤独总比滥情好 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:49

    I prefer this style:

    if (p == NULL) {
        // throw some exception here
    }
    
    DoWhateverWithP();
    

    This means that whatever function this code lives in will fail quickly in the event that p is NULL. You are correct that if p is NULL there is no way that DoWhateverWithP can execute but using a null pointer or simply not executing the function are both unacceptable ways to handle the fack the p is NULL.

    The important thing to remember is to exit early and fail fast - this kind of approach yields code that is easier to debug.

提交回复
热议问题