C++ Logo


Advanced search

Subject: Re: [ub] Justification for < not being a total order on pointers?
From: Nevin Liber (nevin_at_[hidden])
Date: 2013-10-16 11:04:26

On 15 October 2013 17:39, Nevin Liber <nevin_at_[hidden]> wrote:

> Really? I've seen novices ask questions like "does pointer p point to an
> object inside array a?" A natural (but wrong) way to write it is:
> bool isInArray = std::begin(a) <= p && p < std::end(a);
> Can you even write this w/o possibly invoking ub? The only way I can
> think of is O(n), as in:
> bool isInArray = false;
> for (auto q = std::begin(a); q != std::end(a); ++q)
> if (p == q) {
> isInArray = true;
> break;
> }

Could I also please get an answer to this question? This one isn't
theoretical, either.

It turns out that not only was this a novice question, but the novice in
question pointed to almost identical code that was believed by the author
to be C++11 compliant. Since it isn't, how should we recommend he fix it?

I don't believe that casting it to intptr_t or uintptr_t is sufficient,
since you don't get a guarantee that the result is required to preserve the
natural order of the pointers. Is the O(n) solution the only standards
conformant way to do it?

 Nevin ":-)" Liber  <mailto:nevin_at_[hidden]>  (847) 691-1404

SG12 list run by herb.sutter at gmail.com