Boost logo

Boost :

Subject: Re: [boost] Dereferencing End Iterators (Was: Performance Tuning?)
From: Steven Watanabe (watanabesj_at_[hidden])
Date: 2009-07-22 15:36:22


AMDG

Edward Grace wrote:
> Following your minimalistic example, I'm thinking about:
>
> typdef int index;
> int a[3];
>
> index i = 0; // Index idx is homeomorphic to the integers 'cause it
> is one.
>
> i -= 1000;
> i += 2002;
>
> int b=a[i];
>
> That's clearly ok as idx is 2 and the last line is b=*(a + 2).
>
> Whereas.
>
> int *p = a;
>
> p = p - 1000; // Undefined?
> p = p + 1002; // Also undefined?
>
> int b=*p;
>
> Is presumably undefined.
>
> That implies to me that pointer arithmetic is *not* like integer
> arithmetic since the first example is not identical to the second.
>
> Baring in mind the old adage of Mark Twain,
>
> http://www.quotationspage.com/quote/369.html
>
> it seems to me absurd that they are not the same. I guess that's just
> the way it is.

This is also undefined behavior:

int i = 10;
i += std::numeric_limits<int>::max();
i -= std::numeric_limits<int>::max();

So integer arithmetic and pointer arithmetic are
really not very different. The behavior of integer
arithmetic is defined as long as no calculations
overflow (This only applies to signed integers.
unsigned integers are guaranteed to wrap).
The behavior of pointer arithmetic is defined
as long as the pointers stay within the bounds of
the array (allowing for a one past the end, pointer).

In Christ,
Steven Watanabe


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk