1

Given this how does the end() function added in C++ 11 know the end of the array.

Community
  • 1
  • 1
Himanshu
  • 2,384
  • 2
  • 24
  • 42

1 Answers1

4

I'm not sure I understand your question... it could be implemented like this maybe?

namespace std
{
    template<class T, size_t N>
    T *end(T (&arr)[N]) { return &arr[N]; }
}
user541686
  • 205,094
  • 128
  • 528
  • 886
  • You mean that the size N is stored somewhere along with the array? – Himanshu Aug 06 '13 at 06:45
  • 1
    @Himanshu: The size of the array is known at compile time. The template basically extracts that information that the compiler already knew. – Jerry Coffin Aug 06 '13 at 06:48
  • @JerryCoffin you make it sound like you can only this kind of information at compile-time, all the containers in the standard library offer a boundary check and iterators, and they work at runtime too. – user2485710 Aug 06 '13 at 06:58
  • 1
    @user2485710: That is correct but how is it relevant to the question? – user541686 Aug 06 '13 at 07:00
  • 8
    IIRC, in C++ this actually invokes UB due to dereferencing the past-the-end pointer of the array (inside the subscript). The safe way would be `&arr[0] + N`. – Xeo Aug 06 '13 at 07:05
  • @Xeo: I think I read it's safe at some point... if you can provide a reference that would be nice. – user541686 Aug 06 '13 at 07:06
  • @Mehrdad as a consequence, the end() method doesn't really work like that and most importantly, it also works at compile time; even without going into details, it's important to remark that this works at runtime too, otherwise you get the wrong idea. – user2485710 Aug 06 '13 at 07:08
  • 1
    @user2485710: In all honestly I'm not understanding what you're trying to say. Maybe Jerry does? – user541686 Aug 06 '13 at 07:09
  • 1
    @user2485710: An array's type is fixed at compile-time, the function is resolved at compile time (read: instantiated, fixing the `N`) and all that's left for run-time is computing the actual pointer. I really don't see what you're getting at. – Xeo Aug 06 '13 at 07:17
  • 1
    @user2485710: Yes, the standard containers all explicitly track their own size. Most of them need to, because their size can change dynamically. Arrays have a fixed size and nothing to track a "current size", so their size can/must be obtained from the compiler at compile time. – Jerry Coffin Aug 06 '13 at 07:21
  • 1
    So arrays in C++ know their size, just that the programmer doesn't have direct access to it (read N)? – Himanshu Aug 06 '13 at 07:27
  • 2
    @Mehrdad you're the one that has to provide a reference. The standard prefers to state guarantees, not non-guarantees. Asking someone to provide a standard reference for a non-guarantee is dishonest. – R. Martinho Fernandes Aug 06 '13 at 10:57
  • 1
    @R.MartinhoFernandes: [Does this answer _really_ invoke UB](http://stackoverflow.com/q/988158/560648)? See also: http://stackoverflow.com/q/7346634/560648 – Lightness Races in Orbit Aug 06 '13 at 11:16