Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is the NULL pointer < any other pointer (except NULL)?

Tags:

c

pointers

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.

like image 550
becko Avatar asked Jan 16 '23 16:01

becko


2 Answers

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.

like image 105
James McNellis Avatar answered Jan 18 '23 05:01

James McNellis


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

like image 34
Martin Beckett Avatar answered Jan 18 '23 05:01

Martin Beckett