Boost logo

Boost :

From: Sebastian Redl (sebastian.redl_at_[hidden])
Date: 2007-09-03 06:56:12


David A. Greene wrote:
> foo(int *array, int num)
>
> It's perfectly legal to pass (&a[0], 0) to that. It is not legal if a
> is a std::vector, however.
>
1) Declaring a stack array of zero length is illegal in the first place.
(GCC needs the -pedantic compile option to actually fail to compile such
code.)
  int ar[0];
emptyarray.cpp: In function 'int main()':
emptyarray.cpp:7: error: ISO C++ forbids zero-size array 'ar'

2) Assuming that it were allowed, what would be the semantics? GCC gives
sizeof(ar) == 0 (which is a value that does not occur in standard C++),
and (int*)ar as an address on the stack, with some very weird issues:
the address is the same as that of the preceding stack variable, yet
comparing the two addresses seems to yield false. Good indication that
what this thing is doing is ... rather weird.

3) Now, if sizeof(ar) == 0, ar cannot have a legal address - that is,
not one that points into the object, because the object has no size.
GCC's semantics are that it points at a different object. Thus,
dereferencing the pointer is illegal. And the semantics of C++ say that
&ar[0] involves dereferencing, whatever the final code does. So it is
not perfectly legal to do &ar[0] on an empty array.

4) Given that zero-length arrays are not allowed, complaining about the
semantics of &v[0], where v is a zero-length vector, is a strawman
attack. If the array form of the code is correct, the situation cannot
come up in the code that was transformed to use vectors.

5) If you really need to give it an address, pass the null pointer.

Sebastian Redl


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk