4

In C++, unlike in C, an empty array T name[] is illegal,

the type declared is "array of unknown bound of T", which is a kind of incomplete type.

However, it is legal when

used in a declaration with an aggregate initializer

like T name[] = {val1, val2, ...}, where the array is allocated with the number of elements in the initializer list.

What is the expected behaviour when the aggregate initializer is empty? T name[] = {}

I have tested g++ (version 4.8.4) and clang (version 3.4), neither of which give any error or warning, and seem to allocate 1 element. Is this the defined behaviour? Documentation?

int a[] = {};
int b[] = {};

Results in:

a[0] -> 0x7ffc3de28dd8
a[1] -> 0x7ffc3de28ddc
b[0] -> 0x7ffc3de28ddc
b[1] -> 0x7ffc3de28de0
3
  • What versions of gcc and clang? gcc 6.1 and clang 3.8 complain about the array of length 0. Commented Jun 28, 2016 at 17:49
  • gcc 4.8.4, clang 3.4 Commented Jun 28, 2016 at 17:52
  • The addresses of the arrays still have to be valid, so that's probably why something is allocated. But I think dereferencing is undefined behavior when the size of the array is 0. You can get the size of an array literal with: sizeof(a)/sizeof(a[0]) Commented Jun 28, 2016 at 18:03

2 Answers 2

3

From the working draft, [8.5.1/5] (Aggregates):

An empty initializer list {} shall not be used as the initializer-clause for an array of unknown bound.

See also [footnote/105]:

The syntax provides for empty initializer-lists, but nonetheless C++ does not have zero length arrays.

It sounds like an UB.


Note also that this compiles as expected:

template<int N>
void f(int(&)[N]) { }

int main() {
    int v[] = {42};
    f(v);
}

But it doesn't work anymore if you use:

int v[] = {};

Tested with GCC.

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

Comments

2

According to the C++ standard 1.8.6 (C++ 14):

Two objects that are not bit-fields may have the same address if one is a subobject of the other, or if at least one is a base class subobject of zero size and they are of different types; otherwise, they shall have distinct addresses.4

Compiler must allocate at least one element of your arrays to satisfy the above requirement.

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.