The usual approach to getting an array's element count in C in something like this:
#define COUNTOF(arr) (sizeof(arr) / sizeof(arr[0]))
This results in an integral-constant expression, which is a very nice plus as well.
The problem is that it isn't type-safe: int* i; COUNTOF(i); /* compiles :( */
. In practice, this should come up rarely, but for the sake of correctness it would be nice to make this type-safe.
In C++03 this is easy (and in C++11 it's even easier, left as an exercise for the reader):
template <typename T, std::size_t N>
char (&countof_detail(T (&)[N]))[N]; // not defined
#define COUNTOF(arr) (sizeof(countof_detail(arr)))
This uses template deduction to get N
, the size of the array, then encodes that as the size of a type.
But in C we don't get that language feature. This is the small framework I've made:
// if `condition` evaluates to 0, fails to compile; otherwise results in `value`
#define STATIC_ASSERT_EXPR(condition, value) \
(sizeof(char[(condition) ? 1 : -1]), (value))
// usual type-unsafe method
#define COUNTOF_DETAIL(arr) (sizeof(arr) / sizeof(arr[0]))
// new method:
#define COUNTOF(arr) \
STATIC_ASSERT_EXPR(/* ??? */, \
COUNTOF_DETAIL(arr)) \
What can I put in /* ??? */
to get my desired behavior? Or is this impossible?
I'd further prefer answers work in MSVC (i.e., C89), but for the sake of curiosity any definite answer will do.