What is the use of 0-length array (or std::array)?

Your first example is not standard C++ but is an extension that both gcc and clang allow, it is version of flexible arrays and this answer to the question: Are flexible array members really necessary? explains the many advantages of this feature. If you compiled using the -pedantic flag you would have received the following warning in gcc:

warning: ISO C++ forbids zero-size array ‘arr1’ [-Wpedantic]

and the following warning in clang:

warning: zero size arrays are an extension [-Wzero-length-array]

As for your second case zero-length std::array allows for simpler generic algorithms without having to special case for zero-length, for example a template non-type parameter of type size_t. As the cppreference section for std::array notes this is a special case:

There is a special case for a zero-length array (N == 0). In that case, array.begin() == array.end(), which is some unique value. The effect of calling front() or back() on a zero-sized array is undefined.

It would also make it consistent with other sequence containers which can also be empty.

Leave a Comment