For a pointer p, could p < p+1 be false in an extreme case?

c, c++, pointer-arithmetic, pointers

Solution

Is it possible, for a pointer variable `p`, that `p<(p+1)` is false?

If `p` points to a valid object (that is, one created according to the C++ object model) of the correct type, then no. `p+1` will point to the memory location after that object, and will always compare greater than `p`.

Otherwise, the behaviour of both the arithmetic and the comparison are undefined, so the result could be true, false, or a suffusion of yellow.

If yes, under which circumstances can this happen?

It might, or might not, happen with

p = reinterpret_cast<char*>(numeric_limits<uintptr_t>::max);

If pointer arithmetic works like unsigned integer arithmetic, then this might cause a numeric overflow such that `p+1` has the value zero, and compares less than `p`. Or it might do something else.

Problem

Is it possible, for a pointer variable p, that p<(p+1) is false? Please explain your answer. If yes, under which circumstances can this happen? I was wondering whether p+1 could overflow and be equal to 0. E.g. On a 64-bit PC with GCC-4.8 for a C-language program: ``` int main(void) { void *p=(void *)0xFFFFFFFFFFFFFFFF; printf("p :%p\n", p); printf("p+1 :%p\n", p+1); printf("Result :%d\n", p<p+1); } ``` It returns: ``` p : 0xffffffffffffffff p+1 : (nil) Result : 0 ``` So I believe it is possible for this case. For an invalid pointer location it can happen. This is the only solution I can think of. Are there others? Note: No assumptions are made. Consider any compiler/platform/architecture/OS where there is a chance that this can happen or not.

Original source

Related problems