Home > Article > Backend Development > Should You Explicitly Check for NULL Pointers in C/C ?
Checking for NULL Pointers in C/C : Comparison of Methods
In code reviews, the topic of NULL pointer checking often arises. One contributor advocates for using explicit comparisons with NULL:
int * some_ptr; // ... if (some_ptr == NULL) { // Handle null-pointer error } else { // Proceed }
Another party believes that implicitly checking for NULL by using the pointer variable in an if statement is equally clear:
int * some_ptr; // ... if (some_ptr) { // Proceed } else { // Handle null-pointer error }
This latter method is preferred for several reasons. Firstly, it avoids the risk of introducing logical errors such as assigning NULL to the pointer variable instead of comparing it:
if (some_ptr = NULL)
Secondly, it is compatible with C classes like unique_ptr, shared_ptr, and auto_ptr that act as pointers but provide conversions to boolean. An explicit comparison to NULL would require a conversion to a pointer, which may have side effects or be less efficient.
Explicit comparisons to NULL are unnecessarily verbose and introduce potential confusion. The C language explicitly states that non-zero values in boolean contexts are true, and zero values are false. Using implicit checks for NULL is clear and concise, expressing the intent of the code without redundant specificity.
The above is the detailed content of Should You Explicitly Check for NULL Pointers in C/C ?. For more information, please follow other related articles on the PHP Chinese website!