Another question about the C standard. I have tested this and I always get NULL < ptr
true, where ptr
is any pointer different from NULL
. But I know that the Standard says that pointer arithmetic and comparison is only defined inside the bounds of an array. I'm just not sure if the particular comparison NULL < ptr
is legal.
Edit: I have been reading K&R and I found the following quote:
Any pointer can be meaningfully compared for equality or inequality with zero. But the behavior is undefined for arithmetic or comparisons with pointers that do not point to members of the same array.
I'm not sure if this affects the answers already given to this question. In any case, I am still unsure whether p > NULL
is always guaranteed or not to return true, where p
is a pointer !=NULL
.
NULL < ptr
is invalid: a null pointer cannot be relationally compared. To do so yields undefined behavior.
You are correct that you can only relationally compare pointers that point into the same object (either to elements in an array or subobjects of an aggregate). Since a null pointer does not point at any object, you can't relationally compare it with anything.
Only comparison with another NULL (=true) or not (=false) is defined.
NULL is generally defined as zero so will generally compare as less than, but really it's not defined
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