1

In C, is it OK to compare pointers to NULL using the < or > operators? Or is that undefined behavior?

if (NULL < p) {
   // Is this comparison always true?
   // Or is it undefined behavior?
}

I remember hearing somewhere that < comparison is only well-defined if the two pointers point to the same "object". But what about NULL pointers?

hugomg
  • 68,213
  • 24
  • 160
  • 246
  • Comparing pointers with relational operators is indeed UB, unless they are pointing within the same object (array or aggregate type). See http://port70.net/~nsz/c/c11/n1570.html#6.5.8p5 – Eugene Sh. Dec 07 '20 at 18:44
  • Very similar question asked today but in C++: https://stackoverflow.com/q/65185742/10871073 – Adrian Mole Dec 07 '20 at 18:45
  • @ShadowRanger: That question seems to be focusing more about void pointers and it isn't clear to me what the behavior should be for null pointers. That said, the other question that Adrian linked to does seem similar to this one. Thanks! – hugomg Dec 07 '20 at 18:48

0 Answers0