Home >Backend Development >C++ >Should You Use `if (ptr == NULL)` or `if (ptr)` for Null Pointer Checks in C/C ?

Should You Use `if (ptr == NULL)` or `if (ptr)` for Null Pointer Checks in C/C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 07:17:02703browse

Should You Use `if (ptr == NULL)` or `if (ptr)` for Null Pointer Checks in C/C  ?

What's the Best Way to Check for NULL Pointers in C/C ?

In a recent code review, a contributor asserted that all NULL pointer checks should be performed with an explicit comparison to NULL:

<code class="cpp">int * some_ptr;
// ...
if (some_ptr == NULL)
{
    // Handle null-pointer error
}
else
{
    // Proceed
}</code>

This approach was opposed by another reviewer, who argued that the traditional method of using a pointer variable in an if statement is also a valid and concise way to check for NULL:

<code class="cpp">int * some_ptr;
// ...
if (some_ptr)
{
    // Proceed
}
else
{
    // Handle null-pointer error
}</code>

. Which method do you prefer and why?

According to the preferred answer, the latter method is preferable for several reasons:

  • Simplicity: The if (ptr) or if (!ptr) syntax is simple and intuitive.
  • Compatibility with C classes: C classes such as unique_ptr and shared_ptr provide a conversion to bool that enables this idiom.
  • Avoidance of errors due to accidental assignment: The == operator can lead to errors such as if (some_ptr = NULL), which can be difficult to find and debug.

In conclusion, when checking for NULL pointers in C/C , the preferred method is to use the idiomatic if (ptr) or if (!ptr) syntax. This approach is clear, concise, and compatible with C classes.

The above is the detailed content of Should You Use `if (ptr == NULL)` or `if (ptr)` for Null Pointer Checks in C/C ?. 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