Can you compare nullptr to other pointers for order? Is it always smaller?

Can you compare nullptr to other pointers for order?

No, you cannot have ordered comparisons of nullptr or other null pointer constants with pointers.


For the rest of my answer, I cover "Can you compare pointer with a null value to other pointers for order?"

Yes. But whether the result is useful is another matter.

Is it always smaller?

No. Unless the other operand is also null, neither operand is guaranteed to compare greater or smaller in this case.

Standard quote (latest draft):

[expr.rel]

The result of comparing unequal pointers to objects is defined in terms of a partial order consistent with the following rules:

  • [does not apply] If two pointers point to different elements of the same array, or to subobjects thereof, the pointer to the element with the higher subscript is required to compare greater.
  • [does not apply] If two pointers point to different non-static data members of the same object, or to subobjects of such members, recursively, the pointer to the later declared member is required to compare greater provided the two members have the same access control ([class.access]), neither member is a subobject of zero size, and their class is not a union.
  • [applies] Otherwise, neither pointer is required to compare greater than the other.

You should use std::less to compare pointers if you need a strict total order. Null is still not guaranteed to compare as smallest value.


No. Less-than comparisons involving a nullptr do not have specified behavior, and while they do not involve undefined behavior the results are not even guaranteed to be consistent.

The guarantees provided by < on pointers are extremely limited. Even comparing two separately heap-allocated objects is not guaranteed to be consistent (for that you need std::less, which will consistently place a null pointer somewhere in the ordering but not at a standard-defined place). The best you can say is that no pointer to an object will compare equal to a nullptr.