Last Updated: September 29, 2021
·
94.24K
· NIA

Better getting array size in C++

Ever happened to write something like this?

int arr[] = {1, 2, 3, 4, 5};
some_function( arr, sizeof(arr)/sizeof(arr[0]) );

Here the size of array is detected by compiler because it has value list in its initialization. But some_function wants to know its size, so we get it by dividing size of array by the size of its elements. Quite long.

If it is C++, not C, we can use the power of templates in this case:

template<size_t SIZE, class T> inline size_t array_size(T (&arr)[SIZE]) {
    return SIZE;
}

Another feature of C++ is also used here: array reference. When a function has an argument int (&a)[10] it means that it will only accept int arrays of size 10. But here the type T and the size SIZE are template parameters, so we have the reversed process: instead of checking given array with this parameters T and SIZE (as they are unknown), compiler infers this parameters from given argument. Given such array_size defined, the call to some_function can be rewritten like this:

int arr[] = {1, 2, 3, 4, 5};
some_function( arr, array_size(arr) );

In this case, when compiling the call to array_size, compiler guesses that T should be int and SIZE should be 5 because it is possible to pass arr only to array_size<5, int>. As far as T and SIZE are inferred unambiguously, <5, int> can be omitted.

Finally, you see that it is much shorter and much clearer (more important) than sizeof variant!

2 Responses
Add your response

If your compiler supports C++11, you can use std::array[1] which is a lightweight (and safe) wrapper around C style arrays.

[1] http://en.cppreference.com/w/cpp/container/array

over 1 year ago ·

not sure what happened but somebody can help explain it. <a href="http://jerrysproductreviews.blogspot.com/2018/06/skylink-hdtv-antenna-review-cut-cord.html">skylink antenna review</a>

over 1 year ago ·