Home  >  Article  >  Backend Development  >  Is it Safe to Check for Non-Null Pointers with `if(pointer)` Instead of `if(pointer != NULL)`?

Is it Safe to Check for Non-Null Pointers with `if(pointer)` Instead of `if(pointer != NULL)`?

Barbara Streisand
Barbara StreisandOriginal
2024-11-04 01:01:03744browse

Is it Safe to Check for Non-Null Pointers with `if(pointer)` Instead of `if(pointer != NULL)`?

Checking for Non-Null Pointers: if(pointer) vs. if(pointer != NULL)

Question:

Is it acceptable to verify a pointer's non-null status using if(pointer) instead of the conventional if(pointer != NULL)?

Answer:

Yes, this is permissible. Using if(pointer) is safe because the null pointer is implicitly converted to the boolean value false, while non-null pointers are converted to true. This behavior is defined in the C 11 standard under the section on Boolean Conversions:

"A prvalue of arithmetic, unscoped enumeration, pointer, or pointer to member type can be converted to a prvalue of type bool. A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. A prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false."

The above is the detailed content of Is it Safe to Check for Non-Null Pointers with `if(pointer)` Instead of `if(pointer != NULL)`?. 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