0

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.

Sankar V
  • 4,794
  • 3
  • 38
  • 56
Hal Canary
  • 2,154
  • 17
  • 17
  • 7
    In C++11, the first example should be replaced by `if (x == nullptr)` – Andy Prowl Apr 11 '13 at 13:58
  • 3
    in c++, the latter is preferred, but you shouldn't be using raw pointers in C++ in the first place – dchhetri Apr 11 '13 at 13:58
  • 1
    Do whatever your team does. Or not. I would expect no one to have trouble reading code with either of those. If I was doing a code review I would wonder why the function is returning a null pointer in the first place, or why it is returning a pointer a character at all but never question the null check itself. – R. Martinho Fernandes Apr 11 '13 at 14:00
  • 2
    The former is much clearer only if you are not familiar with the latter. – Pete Becker Apr 11 '13 at 14:01
  • At our company you are encouraged to use the former and remove the latter. – Bryan Olivier Apr 11 '13 at 14:04
  • If using `==`, I would check for `NULL == x`, as there's less chance of miss-typing it as an assignment. If I accidentally miss off an equals, the compiler will complain rather than set `x` to `NULL`. – icabod Apr 11 '13 at 14:04
  • Duplicate: *[C/C++ Checking for NULL pointer](http://stackoverflow.com/questions/3825668)* – Peter Mortensen Jan 27 '16 at 13:29

1 Answers1

5

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.

Halim Qarroum
  • 13,985
  • 4
  • 46
  • 71