There is an array
:
...
int score[3];
...
score[0] = 6;
score[1] = 4;
score[2] = 7;
How to get the array's number of elements ? ( here it is obvious but I want to ask a question in general )
There is an array
:
...
int score[3];
...
score[0] = 6;
score[1] = 4;
score[2] = 7;
How to get the array's number of elements ? ( here it is obvious but I want to ask a question in general )
Several ways:
std::distance(std::begin(score), std::end(score))
std::extent<decltype(score)>::value
std::size(score)
See also this answer.
Usually it is a sizeof(score) / sizeof(score[0])
. The advantage of this method is understanding of how array works. And it may be the fastest one too, since sizeof
works at compile time and whole expression could be optimized by compiler.
You can write a macro for that.
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof(*arr))
You should make yourself familiar with containers (like std::vector
) which C++ offers. Many of them have methods that can give you actual count of elements stored (size()
or length()
).
Regarding C-style arrays, in scenarios where they are passed to function as argument, their size is not known, because an array is just a const pointer.