These days I am reading the C++ primer. The book says that, to get the length of a C-Style array, you can use the function std::begin and std::end to get two pointers and subtract them . However, I knew that I can also use sizeof(a)/sizeof(a[0])
if a
is a C-Style array. So which way is better, or they just have little differences?

- 2,109
- 2
- 16
- 23

- 13
- 2
-
This has been discussed in detail in [this SO question](https://stackoverflow.com/questions/4108313/how-do-i-find-the-length-of-an-array) – nada Oct 14 '19 at 06:50
-
The best way to get the size is to not throw it away in the first place. `const count = 5; int array[count];`. – Pete Becker Oct 14 '19 at 12:52
2 Answers
The best way to go nowadays (C++17 and above) is std::size
:
#include <iterator>
...
int arr[5];
static_assert(std::size(arr) == 5);
If you don't have access to C++17, it's pretty easy to roll your own too:
template <class T, size_t N>
constexpr size_t size(const T (&arr)[N]) { return N; }
Even better, just use std::array
, and use it's size member:
std::array<int, 5> arr;
static_assert(arr.size() == 5);

- 4,569
- 1
- 21
- 27
The method with std::begin
and std::end
is a better one because it is safer. So is std::size
.
If you by mistake use the sizeof(a)/sizeof(a[0])
method on a pointer instead of an array, the compiler will likely tell you nothing, and you will get a meaningless result. The other methods will result in a compilation error, and you will know you are trying to do something wrong.
One drawback of the std::begin
and std::end
method is that the result is not a constant expression. The result of std::size
is, so this should be a preferred method of getting the size of a C-style array.

- 112,515
- 14
- 128
- 243
-
Can the difference between `std::begin` and `std::end` be computed at compile time? Otherwise, there may be a runtime overhead to calculate the size. – Empty Space Oct 14 '19 at 07:15
-
@TrickorTreat It can be though there's no guarantee. https://godbolt.org/z/ZPzjfG – n. m. could be an AI Oct 14 '19 at 09:43