3

The standard states:

Unless both pointers point to elements of the same array object or one past the last element of the array object, the behavior is undefined.

Why is it valid to reference one past the last element?

wulfgarpro
  • 6,666
  • 12
  • 69
  • 110

1 Answers1

5

It's okay to compute that pointer and compare to it only. The reason being that it can be used to pass and iterate over and array using a pair of pointers.

If it was not allowed by the standard, the following loop would have exhibited undefined behavior by the mere existence of pend

int arr[100] = {0};

for (int *pbegin = arr, *pend = arr + 100; pbegin != pend; ++pbegin)
{
  // do stuff
}

This is especially important in C++, where the idiom of passing a range as "an iterator to the beginning and one-past the end" is used heavily by the standard library.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
  • OK, so it's what I had expected. But, why then is it undefined to `... *pendAndOne = arr + 101; pbegin != (pendAndOne - 1); ...` – wulfgarpro Jan 22 '17 at 09:08
  • 1
    @wulfgarpro - Because that's what the standard committees decided. Making a single exception to facilitate a useful idiom seemed reasonable to them. Leaving everything else as undefined behavior allows different implementations to support vastly different environments. – StoryTeller - Unslander Monica Jan 22 '17 at 09:12
  • @wulfgarpro If `... *pendAndOne = arr + 101;` is allowed, then what about `... *pendAndOne = arr + 102;` ? ... – songyuanyao Jan 22 '17 at 09:14
  • @songyuanyao arr + 101 is undefined behavior. – 2501 Jan 22 '17 at 09:15
  • 3
    @wulfgarpro One-past-the-end pointers were useful and already worked on all existing implementations when the standard was written. When you go further than one, that's not very useful, and there were implementations where it's going to break (though possibly you'd need to go further than two past the end) or behave in ways the standard couldn't describe (such as pointing back into `arr` again), so there was no point in standardising that. –  Jan 22 '17 at 09:15
  • @hvd, great information, thanks – wulfgarpro Jan 22 '17 at 09:16