Last Updated: June 20, 2018

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!

Say Thanks

3 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 ·

Visit to your My Premier Credit Card account https://mypremiercreditcard.me/ to which the firm will certainly send you your username.

2 months ago ·

To see more than a man setting about http://beardtrimmeruserguide.webstarts.com/index.html The bulk function the precise very same method as http://beardtrimmercondition.doodlekit.com/ also cut in the exact same location, a cord may not bother http://beardtrimmertypes.greatwebsitebuilder.com/ these will certainly provide you the most control https://beardtrimmersettings.page.tl/ If you believe that costs this on a trimmer is as well a lot, http://beardtrimmershop.strikingly.com/ you can find the grooming weapon completely fit to your requirements.

about 2 months ago ·