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

Improve ARRAY_SIZE()

    XMLWordPrintable

    Details

    • Type: Enhancement
    • Status: Resolved
    • Priority: P4
    • Resolution: Fixed
    • Affects Version/s: 16
    • Fix Version/s: 16
    • Component/s: hotspot
    • Labels:
    • Subcomponent:
    • Resolved In Build:
      b08

      Description

      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

      {code:c++}
      // 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))
      {code}

      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>)

      {code:c++}
      template<typename T, size_t N>
      constexpr size_t size(const T (&array)[N]) noexcept;
      {code}

      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.

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              kbarrett Kim Barrett
              Reporter:
              kbarrett Kim Barrett
              Votes:
              0 Vote for this issue
              Watchers:
              1 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: