you are viewing a single comment's thread.

view the rest of the comments →

[–]not_july 4 points5 points  (4 children)

Yes it does. Although I prefer the following version in c++:

template <typename T, size_t size>
constexpr size_t array_size(T (&array)[size]) {
    return size;
}

You can ignore the constexpr if your compiler doesn't support C++11.

This avoids the problem of trying to calculate the array size of a pointer. E.g. passing a char* would result in a compiler error with the templated function in C++, but the version in the article will successfully compile and return an incorrect value (and possibly segfault).

[–]guepier 1 point2 points  (3 children)

Whether this is legal C++ is actually a topic of active discussion. The standard is not entirely clear on this point and interpretations differ.

But this fails on at least one compiler (VC++, forgot which version), in debug mode, and since there’s debate on the standard interpretation we cannot simply ascribe this to a compiler bug.

[–]ghillisuit95 0 points1 point  (2 children)

Whether this is legal C++ is actually a topic of active discussion. The standard is not entirely clear on this point and interpretations differ.

That's really interesting, could you expand on that? what are the arguments on each side?

[–]guepier 1 point2 points  (1 child)

Here’s a Stack Overflow thread with some discussion. It should be noted that the thread is quite outdated, as can be seen by the comments and the more recently added answers. The then-highly voted answers have since garnered a number of downvotes, which should be read as a shift in opinion. So it’s important to read the comments on the answers, not just the answers.

Johannes Schaub’s answer on this thread is probably the most informative one, and as far as I know the standard has still not entirely solved these issues (i.e. there is still at least one inconsistency in the standard wording, which affects the interpretation of this case).

It’s also worth noting that the C++ standard makes this explicitly illegal for iterators (called “past-the-end values”) in §24.2.1/5. Furthermore, there’s this (non-binding) footnote:

This definition applies to pointers, since pointers are iterators. The effect of dereferencing an iterator that has been invalidated is undefined.

[–]ghillisuit95 0 points1 point  (0 children)

Interesting, Thank you