From 8a92304b25c55ceefe7b58ad01ff2d7498d3cef5 Mon Sep 17 00:00:00 2001 From: janwas Date: Mon, 1 Oct 2007 19:12:59 +0000 Subject: [PATCH] better ARRAY_SIZE macro that refuses to compile when passed a pointer. this prevents bugs along the lines of the recently reported StringStripper issue. This was SVN commit r5381. --- source/lib/lib.h | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/source/lib/lib.h b/source/lib/lib.h index ff9a26195a..db0960c00f 100644 --- a/source/lib/lib.h +++ b/source/lib/lib.h @@ -57,8 +57,19 @@ const size_t MiB = 1ul << 20; const size_t GiB = 1ul << 30; -/// number of array elements -#define ARRAY_SIZE(name) (sizeof(name) / sizeof(name[0])) +// +// number of array elements +// + +// (function taking a reference to an array and returning a pointer to +// an array of characters. it's only declared and never defined; we just +// need it to determine n, the size of the array that was passed.) +template char (*ArraySizeDeducer(T (&)[n]))[n]; + +// (although requiring C++, this method is much better than the standard +// sizeof(name) / sizeof(name[0]) because it doesn't compile when a +// pointer is passed, which can easily happen under maintenance.) +#define ARRAY_SIZE(name) (sizeof(*ArraySizeDeducer(name))) //-----------------------------------------------------------------------------