Thursday, April 10, 2008

C++ array size determination

My current project has me working with C-style C++ arrays. In order to make things easier and safer I created some helper templates.

Lets start with finding the the number of elements in an array. The conventional C way would be to use sizeof like:
  sizeof(array)/sizeof(array[0])
I'm not a big fan of this approach. I have seen production code by seasoned C++ developers that looks like this:
  const char* tmp = 0;
// ...
int size = sizeof(tmp)/sizeof(tmp[0]);
Of course this is sometimes hidden behind a macro:
  #define array_size(array) (sizeof(array)/sizeof(array[0]))
// ...
int size = array_size(tmp);
Either way, this gives the wrong answer. The developer, of course, is not interested in what the size of a pointer to an element divided by the size of an element is.

So, can we do better? Actually, yes, we can.
  template <typename T, size_t N>
inline
size_t array_size(const T (&lhs)[N])
{
return N;
}
Here we pass an array by reference to array_size() that extracts the size of the array and returns it. I talked briefly about array passing a few years ago.

We can now use it like so:
  int ia[10];
size_t s = array_size(ia); // s == 10
And if we try to use this with a pointer like so:
  const char* tmp = 0;
// ...
size_t s = array_size(tmp); // error
We get a compiler error similar to:
  error: no matching function for call to 'array_size(const char*&)'
Very nice.

However, sizeof can also be used with a type instead of a variable. In my next post, I'll show how we can create a template that will work with a type instead of a variable.

2 comments:

Anonymous said...

Oh, that is wicked cool.... Gotta love templating

Johnry said...

The coderwall explains in Some detail the theory of how best to get the size of an array in C++ https://coderwall.com/p/nb9ngq/better-getting-array-size-in-c