Home > Backend Development > C++ > body text

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

Mary-Kate Olsen
Release: 2024-11-01 13:29:40
Original
973 people have browsed it

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>
Copy after login

instead of the implicit check:

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!