FREE Subscription to Dr. Dobb’s Digest: Same Great Content, New Digital Edition
Site Archive (Complete)
C++
Email
Print
Reprint

add to:
Del.icio.us
Digg
Google
Furl
Slashdot
Y! MyWeb
Blink
March 06, 2007
Counting Array Elements at Compile Time

Improving on COUNTOF

(Page 1 of 7)
Ivan 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:

  • Readable notation.
  • Produces a compile-time constant.
  • Works even for local types.
  • Works on older compilers (Visual C++ 6, for instance).

1 Counting Array Elements at Compile Time | 2 Type Safety | 3 The Built-In Array & Initializer Lists | 4 Unit Testing | 5 Compile-Time Assertions | 6 Implementation | 7 Arrays as Function Arguments Next Page
TOP 5 ARTICLES
No Top Articles.



MICROSITES
FEATURED TOPIC

ADDITIONAL TOPICS

INFO-LINK