Checking Pointer Values: if (pointer) vs if (pointer != NULL)
When working with pointers in C , it is crucial to determine their validity. Can you simply use the expression if (pointer) to test if a pointer is non-NULL? Or do you need to explicitly write if (pointer != NULL)?
Answer:
The C standard allows you to use if (pointer) to test for pointer validity. Non-null pointers are implicitly converted to true, while the null pointer is converted to false. This behavior is defined in the C 11 standard's section on Boolean Conversions:
<code class="cpp">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.</code>
Therefore, you can safely write if (pointer) to check if a pointer is non-NULL. However, for clarity and consistency, it is recommended to use the explicit if (pointer != NULL) or if (pointer) construction as appropriate.
The above is the detailed content of Is `if (pointer)` Enough to Check Pointer Validity in C ?. For more information, please follow other related articles on the PHP Chinese website!