1

I am learning/reading a bit of openGL. I am currently following the tutorials from http://www.arcsynthesis.org/gltut/ . The program has a macro which is used for array length. I know array length is counted as (sizeof( array ) / (sizeof( array[0] ).

But the code has some additional stuff so the final macro is :

#define ARRAY_COUNT( array ) (sizeof( array ) / (sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*))))

I am unable to understand why is it being multiplied by a bool.

3
  • It's "protecting" itself against being used on pointers. Commented Aug 17, 2014 at 13:39
  • Indeed. But it's non-robust, and it's arguable that returning 0 is not helpful. Commented Aug 17, 2014 at 13:40
  • Yeah, it seems pretty pointless. If you have a char *, sizeof(arr[0]) <= sizeof(void *) must be true, so it will still count. Considering this is C++, you can write a constexpr function to achieve the same thing, or a regular one to have the result at runtime. Of course you could also just use std::array or boost::array. Commented Aug 17, 2014 at 13:41

1 Answer 1

1

The addition is to check some bad usages of pointer instead of array as:

long long buf[42];
long long *p = buf; 

ARRAY_COUNT(p); // this produces a compilation error : division by zero.

but it fails to detect some bad usages as:

char buf[42];
char *p = buf; 

ARRAY_COUNT(p); // this gives unexpected result.

The check cannot detect bad usage for types which have a size less or equal than a pointer.

The C++ way to do that is:

template <typename T, std::size_t N>
constexpr std::size_t ArraySize(T (&)[N]) { return N; }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.