Checking for null before pointer usage

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

    How about: a comment clarifying the intent? If the intent is "this can't happen", then perhaps an assert would be the right thing to do instead of the if statement.

    On the other hand, if a null value is normal, perhaps an "else comment" explaining why we can skip the "then" step would be in order. Stevel McConnel has a good section in "Code Complete" about if/else statements, and how a missing else is a very common error (distracted, forgot it?).

    Consequently, I usually put a comment in for a "no-op else", unless it is something of the form "if done, return/break".

提交回复
热议问题