Home  >  Article  >  Backend Development  >  Explicit vs. Implicit NULL Checks in C/C : Which Approach Is Better?

Explicit vs. Implicit NULL Checks in C/C : Which Approach Is Better?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 13:29:40974browse

Explicit vs. Implicit NULL Checks in C/C  : Which Approach Is Better?

Pointer Nullity Verification in C/C

In a code review discussion, a contributor has advocated for the use of explicit NULL checks in the following format:

<code class="c">int * some_ptr;
if (some_ptr == NULL) { ... }</code>

instead of the implicit check:

<code class="c">int * some_ptr;
if (some_ptr) { ... }</code>

This raises the question of which approach is preferred and why.

Explicit NULL Comparison

The explicit NULL comparison is more explicit in its intention, clearly stating that the pointer must not be NULL. It also guards against accidental assignment, as the following is invalid:

<code class="c">if (some_ptr = NULL) { ... }</code>

Implicit NULL Check

The implicit NULL check is more concise and less likely to introduce bugs due to assignment errors. It relies on the fact that a pointer variable in an if statement is implicitly evaluated as its truthiness (non-NULL or NULL).

Recommendation

In general, it is preferable to use the implicit NULL check for the following reasons:

  • It is more concise and succinct.
  • It does not depend on the definition of the NULL symbol.
  • It can be used with C classes that provide a conversion to bool.

Exception

However, there are cases where the explicit NULL comparison may be more appropriate, such as when:

  • Exceptional clarity is required.
  • The code may be interpreted by non-C programmers.
  • The code is heavily optimized and the implicit check could lead to unnecessary overhead.

The above is the detailed content of Explicit vs. Implicit NULL Checks in C/C : Which Approach Is Better?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn