14

In C++11 it allows you to create a 0 length C array and std:array like this:

int arr1[0];
std::array arr2<int,0>;
  1. So I'm thinking what is the use of a array that doesn't have a space to store?
  2. Secondly what is the zero length array? If it is a pointer, where does it pointing to?
17
  • 3
    gcc.gnu.org/onlinedocs/gcc/Zero-Length.html Commented Oct 6, 2014 at 2:07
  • 9
    No, C++ doesn't allow zero-length arrays. Even if it did, it wouldn't be a pointer. Commented Oct 6, 2014 at 2:09
  • 4
    @NayanaAdassuriya: Yes, many compilers (including GCC) have extensions. Compile with -pedantic (or even -pedantic-errors) if you want to stick to standard-compliant code. Commented Oct 6, 2014 at 2:18
  • 2
    An array of 0 length does have a pointer. Just don't try to write to it. Commented Oct 6, 2014 at 2:24
  • 2
    @MikeSeymour: There's no zero-length array type. However, there are definitely zero-length arrays: new int[0] is valid. Commented Oct 6, 2014 at 9:16

1 Answer 1

21

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.