Home >Backend Development >C++ >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:
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!