
On 6/25/06, me22 <me22.ca@gmail.com> wrote:
I think it's worth including. It's not all that uncommon; even Freenode/##C++'s channel bot has the following factoid: Don't use sizeof() to get the size of an array, because sizeof() will do the wrong thing if that 'array' is actually a pointer. Use the following instead: template <typename T, size_t N> size_t array_size(T (&)[N]) { return N; }
The downside of that is that it doesn't yield a compile-time constant, so you can't use it, for instance, as the size of another non-dynamically allocated array, nor for template metaprogramming, etc. For my projects, I do something like: #include <cstddef> namespace boost { template< typename Type, ::std::size_t Size > char (&array_size_impl( Type (&)[Size] ))[Size]; } #define BOOST_ARRAY_SIZE( array ) sizeof( ::boost::array_size_impl( array ) ) //////////////////////// The benefit of the above is that in addition to giving an easy-to-read compile-time an error when attempting to pass a pointer, it also yields a compile-time constant value. -- -Matt Calabrese