1

VC provides a macro called "_countof" inside "stdlib.h", will calculates in compile time, the number of an array's elements.

My question is does gcc provide a similar utility? Thanks.

Hind Forsum
  • 9,717
  • 13
  • 63
  • 119
  • I don't think GCC has it directly, but search the Linux source for the `ARRAY_SIZE` macro which builds on a couple other macros that ultimately use a GCC extension to ensure that `ARRAY_SIZE` is only used on arrays. – Michael Burr Apr 17 '17 at 02:15
  • Possible duplicate of [How to determine the length of an array at compile time?](http://stackoverflow.com/questions/3388656/how-to-determine-the-length-of-an-array-at-compile-time) – Pyves Apr 17 '17 at 09:33

1 Answers1

2

In C++17, the std::size function template will return the size of an array or container.

A possible implementation is given, so you can write your own until C++17 becomes available:

template <class T, std::size_t N>
constexpr std::size_t size(const T (&array)[N]) noexcept
{
    return N;
}

This will work on any conforming C++11 compiler, so it is a lot more portable than compiler-specific extensions.

Brian Bi
  • 111,498
  • 10
  • 176
  • 312