How to get the size of an array

(Pharap) #1

I think a lot of people have trouble with knowing how to get the size of an array,
so a while ago I created a function for getting the size of an array,
and a demo showing how to use that function.

(By size, I mean the number of elements in the array,
not the size in bytes - that’s what sizeof is for.)

I recently spent a few hours filling in the README to explain how it works,
and why the function should be implemented in that particular way,
so I’ve decided to make a thread linking to it in the hopes that people will have an easier time finding out about it,
and in the hopes that people will find it useful:

Essentially the function is:

template< typename Type, size_t size >
constexpr size_t getSize(const Type (&)[size]) noexcept
{
	return size;
}

And it’s used like:

// An example array
int example[4];

// Gets 4
constexpr size_t size = getSize(example);

You can also use it in loops:

// An example array
int example[4];

for(size_t index = 0; index < getSize(example); ++index)
{
	int value = example[index];
}

(You could use a ranged for loop instead, but sometimes you need the index.)

And it will also work on arrays in progmem.

2 Likes
(Kevin) #2

When you say size, you mean the amount of bytes that the array takes in memory?

(Pharap) #3

No, there’s already sizeof(array) for that.

I mean the number of elements.
Or to put it more formally, the extent of the 0th dimension of the array.

It might seem odd, but most C++ literature does actually call the number of elements the ‘size’ of the array.
Hence std::size, which this function is a substitute for,
though std::size works for more than just arrays and this doesn’t.

I’ve made an edit in the first post to specify this.

(Kevin) #4

Oh there is no len()?

(Pharap) #5

Not until C++17, when they added std::size.

I think part of the reason for the delay is that C++11 introduced std::array which is intended to replace ‘raw’ arrays,
but eventually they realised the benefit of a free function that works on both raw arrays and container types.

(It also took until C++17 to get a std::clamp function.)

1 Like
(Kevin) #6

Well this is news to me, I was unaware that C ran its arrays without a class (that has helper functions).

(Pharap) #7

This is C++, not C.

C doesn’t have classes anyway, so I’m not sure what you mean.

1 Like
(Kevin) #8

Whatever I meant C++ I’m pretty bad at making the difference on all that stuff. That’s why we have you :slight_smile:

3 Likes