Best Practices: how to check for NULL return value in C/C++ [closed]

橙三吉。 提交于 2019-12-25 05:03:33

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/15950688/best-practices-how-to-check-for-null-return-value-in-c-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!