Home >Backend Development >C++ >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:
Exception
However, there are cases where the explicit NULL comparison may be more appropriate, such as when:
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!