I know that NULL == (void *)0 but it is mentioned that it can be represented as a value which doesn't contain all zeros. What bothers me is if those pieces of code are equivalent for all (any_type *):
any_type *val;
if (val) { ... };
and
if (val != NULL) { ... };
Yes. You can use the macro NULL in this way. It is a null pointer constant which is equal to 0.
When C requires the Boolean value of an expression, a false value is inferred when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes
if(expr)where
expris any expression at all, the compiler essentially acts as if it had been written asif((expr) != 0)Substituting the trivial pointer expression
pforexpr, we haveif(p) is equivalent to if(p != 0)and this is a comparison context, so the compiler can tell that the (implicit)
0is actually a null pointer constant, and use the correct null pointer value. There is no trickery involved here; compilers do work this way, and generate identical code for both constructs. The internal representation of a null pointer does not matter.
but it is mentioned that it can be represented as a value which doesn't contain all zeros.
Yes. True. But representation doesn't matter in this case:
Whenever a programmer requests a null pointer, either by writing
0orNULL, it is the compiler's responsibility to generate whatever bit pattern the machine uses for that null pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With