Best Practices: how to check for NULL return value

2019-08-17 16:55发布

This is a style question for C and C++. Do you prefer

void f() {
  const char * x = g();
  if (x == NULL) {
    //process error
  }
  // continue function
}

or this:

void f() {
  const char * x = g();
  if (! x) {
    //process error
  }
  // continue function
}

? The former is much clearer, but the latter is less verbose.

标签: c++ c null
1条回答
\"骚年 ilove
2楼-- · 2019-08-17 17:48

It mainly depends on the adopted convention within your group of work.

As the != NULL form may be clearer to a developer who is used to it, the inverse is also true for developers who were used to check a NULL value using the boolean form.

As @Andy Prowl mentioned it, a much clearer version of this appeard in C++11 by the use of the nullptr type : if (x == nullptr). This notation should be used as a convention by every members of a team if you are writing C++11 application.

Finally, there exists different patterns that are pretty much used such as the Null Object Pattern that avoids making this check everywhere in your code, in case this check involves a specific habit of your application.

查看更多
登录 后发表回答