Array size type safe at compile time

suggest change
// :glot
#include <iostream>
#include <iterator>

auto main()
    -> int
{
    constexpr int a[] = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
    constexpr auto n = std::ssize(a);
    int b[std::size(a)] = {}; // An array of the same size as a.
    
    (void) b;
    std::cout << "Size = " << n << '\n';
}
Size = 10

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.

In C++11 you can do:

std::extent<decltype(MyArray)>::value;

Example:

// :glot
#include <iostream>
#include <type_traits>

int main()
{
    char MyArray[] = { 'X','o','c','e' };
    const auto n = std::extent<decltype(MyArray)>::value;
    std::cout << n << "\n";
}
4

Before C++17, obtaining an array's size safely required a helper function or a type trait such as std::extent. std::extent yields 0 for a pointer type, so it does not diagnose that mistake; a function template taking T (&)[N] does. C++17 added std::size, and C++20 added std::ssize for a signed result, as used in the first example.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents