The traditional way to find the number of elements in an array in C++ has been to calculate it using the sizeof operator. For example, to loop over the elements of an array, you might write this code:
long a[] = { 2, 3, 5, 7, 11 }; int count = sizeof(a)/sizeof(a[0]); for ( int i = 0; i != count; ++i ) /* ... process a[i] ... */ ;
Sometimes the sizeof expression is wrapped in a macro to make it more readable:
#define COUNTOF(x) \ ( sizeof(x) / sizeof((x)[0]) )
In this article, I present a new type-safe way to write COUNTOF so that it produces a compile-time error if you accidentally pass it a pointer, std::vector, or anything else other than the built-in array. The new version also preserves the good features of the traditional COUNTOF, including:
- Readable notation.
- Produces a compile-time constant.
- Works even for local types.
- Works on older compilers (Visual C++ 6, for instance).