6

I come across the following code, which returns the size of a C style array.

template <typename Type, int N>
int GetArraySize(Type (&array)[N])
{
    (void) sizeof (0[array]);
    return N;
}

The templated part seems to have been already explained in this question.


But still, I don't understand what is the utility of the sizeof line. Any ideas? Some suggest that it is to avoid unused variable warning, but a simpler #pragmacould have been used, right?

Moreover, will this piece of code be effective in any situation? Aren't there any restrictions?

Antoine C.
  • 3,730
  • 5
  • 32
  • 56
  • `#pragma` is not standard (although most mainstream compilers do implement it), but casting to void is – Curious Jun 19 '17 at 09:29
  • `0[array]` is the same as `array[0]` – Pierre Emmanuel Lallemant Jun 19 '17 at 09:29
  • I see no point in sizeof line. `array` parameter name could be omitted to avoid unused variable warning. Also it should use and return `size_t`. – user7860670 Jun 19 '17 at 09:32
  • The compiler is not the only one that needs to understand the code. A named parameter conveys information more clearly to a human reader, in this case that the it is intended than an array be passed. And, once the parameter is named, there may be a wish to not trigger a compiler warning ..... – Peter Jun 19 '17 at 10:07

1 Answers1

10

I think the purpose of the line is to silent unused variable warning. The simpler would be to omit parameter name

template <typename Type, int N>
int GetArraySize(Type (&)[N])
{
    return N;
}
Jarod42
  • 203,559
  • 14
  • 181
  • 302