Old said:
Ike Naar said:
If p does not point to an element of a[max],
(or to "one past the end" of a)
all comparisons (p<a), (p>&a[max-1]) and ((p-a)%sizeof(T)) invoke
undefined behaviour and can evaluate to anything, including 'true'.
So your solution may produce a 'false positive' result.
Is it actually undefined behaviour (ie. program can crash), or
just "undefined result" (ie. unspecified behaviour).
It's actual undefined behaviour by (explicit) omission. It falls
under "all other cases" in the following excerpt:
[C99 6.5.8 Relational operators]
5 When two pointers are compared, the result depends on the
relative locations in the address space of the objects pointed
to. If two pointers to object or incomplete types both point to
the same object, or both point one past the last element of the
same array object, they compare equal. If the objects pointed to
are members of the same aggregate object, pointers to structure
members declared later compare greater than pointers to members
declared earlier in the structure, and pointers to array
elements with larger subscript values compare greater than
pointers to elements of the same array with lower subscript
values. All pointers to members of the same union object
compare equal. If the expression P points to an element of an
array object and the expression Q points to the last element of
the same array object, the pointer expression Q+1 compares
greater than P. In all other cases, the behavior is undefined.
I was assured by one of the WG members for C++ recently that in C++
it is merely unspecified behaviour. It would be notable if the two
languages differed in this respect.
Right: it's unspecified behaviour in C++.
[C++98 5.9 Relational operators]
- If two pointers p and q of the same type point to different
objects that are not members of the same object or elements of
the same array or to different functions, or if only one of them
is null, the results of p<q, p>q, p<=q, and p>=q are
unspecified.
I believe the reason is to allow pointers to work reliably as the keys
of associative containers (set, map, etc.), but you should ask in the
C++ groups if you want a more definitive answer.
Jeremy.