The fact your code compiles at all is because your compiler (gcc?) supports a non-standard extension.
You would be better off using standard containers (e.g. std::vector<int>
if the size is determined at run time, or std::array<int, 6>
if the size is fixed at compile time).
But, for a function that takes a raw array and gives its size, you can simply pass a reference;
int length(const auto &arg) {return sizeof(arr)/sizeof(*arr);}
or
template<int N> int length(const int (&arr)[N])
{
return N;
}
Depending on your needs, the function can also be made constexpr
and noexcept
.
In C++17 and later, simply use the helper function std::size()
(supplied in various standard headers, such as <iterator>
, and works with a raw array as well as standard containers)
int main(){
int arr[] = {1,2,3,4,5,0};
cout << std::size(arr);
return 0;
}