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?

4
  • #pragma is not standard (although most mainstream compilers do implement it), but casting to void is
    – Curious
    Commented Jun 19, 2017 at 9:29
  • 0[array] is the same as array[0]
    – anotherdev
    Commented Jun 19, 2017 at 9: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. Commented Jun 19, 2017 at 9: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
    Commented Jun 19, 2017 at 10:07

1 Answer 1

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;
}
3
  • 3
    Well, this warning could be silenced with (void) array; as well, why put sizeof with fancy indexing there? Commented Jun 19, 2017 at 9:34
  • 2
    Because why not? :D Commented Jun 19, 2017 at 9:37
  • @VTT -- who knows? People spend far too much time thinking of nutty ways to avoid warnings in legal, correct code. Commented Jun 19, 2017 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.