Search code examples
c++comparison-operatorspointer-arithmeticnullptr

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


This question is based on code that I found that monitors possible memory leaks, so it contains some code that you probably don't want to see in regular programs like ordering pointers.

However, I saw that a pointer was set to nullptr and then the pointer was compared to a maximum address. Is it guaranteed by the C++ standard that nullptr is always smaller than other pointers for operator<?


Solution

  • nullptr is always smaller than other pointers for operator<

    No, compare a nullptr with a pointer by a relational operator is not supported by the standard.

    To compare the operands of a relational operator, the following rule will first be applied to both operands, that is expr.rel#2

    The usual arithmetic conversions are performed on operands of arithmetic or enumeration type. If both operands are pointers, pointer conversions and qualification conversions are performed to bring them to their composite pointer type. After conversions, the operands shall have the same type.

    nullptr is not a pointer, instead, it is called a null pointer constant. So, "pointer conversions and qualification conversions are performed to bring them to their composite pointer type" will not apply to it. So, it violates, After conversions, the operands shall have the same type.

    Clang gives a correct diagnosis. Since the code is ill-formed, hence talk about what's the result does not make sense.