Monday, November 22, 2010

Zero Element Arrays

On some compilers the following compiles, on others, it does not: int myArray[0];
    In g++, yes.
    In Microsoft C++, yes.
    In Sun CC, no.
    In the C++ Standard: It used to be not allowed (ISO/IEC 14882:1998(E)). I am not sure if it was later permitted, or some compilers do it as an extension and/or bug.

For size tests, I used g++ to compile. A struct with just an empty array has size 0; so does an object of this struct. Interestingly, an empty struct has 1 byte, so that you are able get the address of a corresponding object. This is different than in C, where an empty struct is zero-bytes. Several zero-byte objects get the same address with g++.

A C++ struct with only non-virtual functions doesn't change the size, but if you add a virtual function, the size typically changes to accommodate a virtual function table pointer.

C++ Standard does allow int *myArray_p = new [0];

C (C90) and C++ allow dynamic arrays such as the following:
  int sizeofArray(int nbrOfElements)
      int myArray[nbrOfElements];
      return sizeof(myArray);
which allows 0 to be passed, and report a size of 0.

Zero-length arrays are not a big consideration for most people. I have only seen it considered with template design.

   C++ Templates by David Vandevoorde and Nicolai M. Jouttis. Addison-Wesley, 2003.
   More Exceptional C++, by Herb Sutter. Addison-Wesley, 2002.

No comments:

Post a Comment