Re: Determining array size

From: John Harrison (john_andronicus_at_hotmail.com)
Date: 06/21/04


Date: Mon, 21 Jun 2004 19:21:33 +0100


"David Rubin" <davidrubin@warpmail.net> wrote in message
news:82b37be.0406211008.2218a3d1@posting.google.com...
> "John Harrison" <john_andronicus@hotmail.com> wrote in message
>
> [snip]
> > template<typename T, size_t N>
> > size_t array_size(T (&dummy)[N]) { return N; }
> >
> > dummy is a reference to an array T of size N. Because the parameter is
> > unused C++ allows you to omit it as AngleWyrm did.
>
> Of course, this generates a function for every different type T and
> size N. It's more efficient to use
>
> #define array_size(X) (sizeof X / sizeof *X)
>
> which has the same semantics. You only lose some type-safety, but this
> typically not a problem.
>
> /david

Not necessarily, if you make the template version an inline function.

Your version suffers from the big problem that is will compile for pointers.
Its quite common for an array to change to a pointer, for instance when some
code is refactored into a different function but the array stays in the
original function and is passed to the new function as a pointer. In that
case your version will compile but give meaningless results. The template
version will give a compile error.

john



Relevant Pages

  • Re: Copying an array slice (Was: Re: Difficulties with passing multi-dimensional arrays)
    ... > the pointer to array of unknown size. ... but it still compiles without a cast. ... unknown at compile time so nothing can be checked. ...
    (comp.lang.c)
  • Re: A taxonomy of types
    ... array semantics, ...) ... you mean "following correct offset operator semantics"... ... What does exist is based exclusively on pointer type. ... they can't be compiled if the compiler does not know how to compile them, ...
    (comp.lang.misc)
  • Re: Idea
    ... This is not a method pointer. ... the *value* of ecx at compile time, so cannot set that part of the constant. ... >> original array would not be valid, in the sense that it would not ... >> have any instance data in the method pointers. ...
    (comp.lang.pascal.delphi.misc)
  • Re: Pointer corruption calling across a DLL boundary
    ... >> Make sure they are compiled using the same compile option. ... which respectively declare a pointer to a pointer and an ... array of indeterminate size of pointers. ... the workaround is to declare a local copy of the ...
    (microsoft.public.vstudio.development)
  • Re: Pointer corruption calling across a DLL boundary
    ... >> Make sure they are compiled using the same compile option. ... which respectively declare a pointer to a pointer and an ... array of indeterminate size of pointers. ... the workaround is to declare a local copy of the ...
    (microsoft.public.dotnet.languages.vc)