#include <iostream>
int main()
{
int arr[4]{0,1,2,3};
int* begin = arr;
int *end = &arr[4];
int *firstElement = &arr[1];
int *lastElement = &arr[3];
int *onePastEnd = &arr[5];
std::cout << firstElement - begin << std::endl; //outputs 1
std::cout << lastElement - begin << std::endl; //outputs 3
std::cout << end - begin << std::endl; //outputs 4
std::cout << onePastEnd - begin << std::endl; //outputs 5
//std::cout << (*(firstElement - begin)); //illegal indirection because you're trying to find out what is at an address, but this is not an address rather difference between two pointers
}
Is this a valid code (according to C++ standard) to point to locations past the last element?
Although the output seems valid, it is confusing because pointing out of range of array may result in an undefined behaviour right? Then how is this code working?
Edit: I am not asking about iterators but rather simple pointers, but the duplicate question is asking about iterators.