March 06, 2007
Counting Array Elements at Compile TimeImproving on COUNTOFIvan J. Johnson
Ivan presents a new type-safe way to write COUNTOF so that it produces a compile-time error if you accidentally pass it to anything other than the built-in array.
Ivan is a Lead Engineer with GE Energy, where he develops software for equipment monitoring and performance optimization. He can be contacted at ijohnson@alum.mit.edu.
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:
|
|
||||||||||||||||||||||||||||||
|
|
|
|