Does if (pointer) Equivalent to if (pointer != NULL)?
In C programming, it's common practice to check if a pointer is not NULL to ensure it points to a valid memory location. Traditionally, this is achieved with the if (pointer != NULL) condition. However, there's a potential alternative syntax: if (pointer).
Is it Safe to Use if (pointer)?
Yes, if (pointer) is a valid syntax and equivalent to if (pointer != NULL). The reason lies in C 's implicit conversion rules.
Implicit Boolean Conversions
According to the C 11 standard 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."
In other words, when a pointer value is used in a boolean context, the compiler implicitly coerces it into a boolean value. A null pointer is treated as false, while all other pointer values are treated as true.
Practical Example
Consider the following code:
<code class="cpp">int* p = nullptr; if (p) { // Do something } else { // Do something else }</code>
In this example, the if (p) condition is valid because the null pointer p is implicitly converted to false. If p were pointing to a valid memory location, the condition would evaluate to true.
Conclusion
While it's technically correct to use if (pointer) instead of if (pointer != NULL), the latter is more explicit and recommended for clarity and readability purposes.
The above is the detailed content of Is `if (pointer)` Equivalent to `if (pointer != NULL)` in C ?. For more information, please follow other related articles on the PHP Chinese website!