Search code examples
cpointersc89

C compare two pointers greater than if one is null


If I compare two pointers in C I am aware of C 6.5.8/5 which says:

pointers to structure members declared later compare greater than pointers to members declared earlier in the structure

That is fine but what if one of the pointers is NULL? I know I can do foo != NULL but for example is this against the standard:

char *bar = NULL;
char *foo = "foo";
if(foo > bar) { function(); }

The section doesn't specifically address NULL in the case of greater than which is why I'm confused. Also if you could tell me if it applies to C89 as well as C99.

To clarify, this has nothing to do with structures that is just the part of the standard I was quoting. The code is very similar to what I describe above. I have some pointers to an array and one of those pointers may be null therefore I'd like to know if it's ok to compare using greater than.


Solution

  • Your example is indeed undefined. As explained in C11, 6.5.8., p5, every rule mandates that pointers point to the same object or one past that object.

    So, two pointers may be compared using relational operators: <, >, <=, >=, only if they point to the same object or one past that object. In all other cases:

    6.5.8. Relational operators,

    1. . In all other cases, the behavior is undefined.

    Pointer with the value NULL, a null pointer, doesn't point to an object. This is explained in:

    6.3.2.3 Pointers

    1. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.