https://codeeval.dev/gist/5323bbd4a2e247a6f2518a9a25dbe808
The C idiom for array size, sizeof(a)/sizeof(a[0])
, will accept a pointer as argument and will then generally yield an incorrect result.
For C++11
using C++11 you can do:
std::extent<decltype(MyArray)>::value;
Example:
https://codeeval.dev/gist/e04ebc7263970571a812dce362729d7d
Up till C++17 C++ had no built-in core language or standard library utility to obtain the size of an array, but this can be implemented by passing the array by reference to a function template, as shown above. Fine but important point: the template size parameter is a size_t
, somewhat inconsistent with the signed Size
function result type, in order to accommodate the g++ compiler which sometimes insists on size_t
for template matching.
With C++17 and later one may instead use [std::size](<http://en.cppreference.com/w/cpp/iterator/size>)
, which is specialized for arrays.