0
template <typename _CountofType, size_t _SizeOfArray>
char( *__countof_helper1( _CountofType(&_Array)[_SizeOfArray]))[_SizeOfArray];

#define _myCountOf(_Array) (sizeof(*__countof_helper1(_Array)) + 0)

I'm trying to understand _countof Macro, but unable to understand how its able to calculate the size of array. Please someone explain bit by bit the above code

oomkiller
  • 169
  • 3
  • 11
  • Above duplicate has specifics for this macro, and also links to more general explanations. – Benjamin Bannier Apr 15 '14 at 15:58
  • Also read: [what are the rules about using an underscore in an identifier/](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797) – Martin York Apr 15 '14 at 16:00

1 Answers1

5

It's an overly complicated declaration. In modern C++, you can do just this:

template<typename T, size_t SizeOfArray>
constexpr size_t countof(T (&array)[SizeOfArray]) { return SizeOfArray; }

The crux of the solution is T (&array)[SizeOfArray]: it's the syntax you need to pass a reference to an array. T and SizeOfArray are inferred by the compiler, so it'll have valid values for any array you throw at it.

In your helper case, the programmer probably didn't have access to constexpr but still wanted to make sure that the expression was evaluated at compile-time rather than at runtime. It's confusing because the C++ function declaration syntax is confusing: it declares a function that accepts an array of any type and length and returns an array of characters of the same length. It then uses sizeof to find the length of the character array and returns that.

zneak
  • 134,922
  • 42
  • 253
  • 328
  • also covered here pretty well: https://stackoverflow.com/questions/437150/can-someone-explain-this-template-code-that-gives-me-the-size-of-an-array – Engineer2021 Apr 15 '14 at 16:00