Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8249945

Improve ARRAY_SIZE()



    • Enhancement
    • Resolution: Fixed
    • P4
    • 16
    • 16
    • hotspot
    • b08


      The ARRAY_SIZE() macro packages up an idiom for getting the compile-time constant number of elements in an array of some arbitrary element type. However, it has the defect that later maintenance that changes the array expression to a pointer type will still quietly compile, but will produce entirely the wrong value, which can be unpleasant to debug. There is a different implementation possible in C++ (the current approach is from C) that avoids that problem, producing a compile-time error in such a situation. Specifically

      // array_size_impl is a function that takes a reference to T[N] and
      // returns a reference to char[N]. It is not ODR-used, so not defined.
      template<typename T, size_t N> char (&array_size_impl(T (&)[N]))[N];

      #define ARRAY_SIZE(array) sizeof(array_size_impl(array))

      Unfortunately, in C++03 this runs afoul of 14.3.1, which forbids local types as template parameters. If the array element type is a local type, this implementation will fail to compile. C++11 removed that restriction.

      Note that C++17 adds (in <iterator>)

      template<typename T, size_t N>
      constexpr size_t size(const T (&array)[N]) noexcept;

      which returns N. However, this doesn't work in constexpr contexts when the argument is a data member, because the implicit reference to {{this}} makes the call not constexpr. So this is not really an eventual replacement for the above ARRAY_SIZE macro.


        Issue Links



              kbarrett Kim Barrett
              kbarrett Kim Barrett
              0 Vote for this issue
              1 Start watching this issue