C++ the meaning of getting size of a array

arrays, c++

Solution

Multiplying `sizeof array[0]` in the divisor by

(sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*))

makes the divisor zero if

sizeof array == sizeof(void*)

and

sizeof array[0] > sizeof(void*)

In those cases, you get a division by zero during the compilation, which would cause the compilation to fail.

These checks are an attempt to detect arguments that are pointers (be they the result of array-to-pointer conversion or not), since one can't know how large an "array" a pointer points to by using that quotient.

It fails if other pointer types have different sizes than `void*`, and it doesn't detect pointers to things that are not larger than `void*`s. It probably does more harm than good by lulling the author in a false sense of security.

Problem

Here is a macro for getting array size ``` #define array_size(array) \ (sizeof( array ) / (sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*))) ``` I think normally (sizeof( array ) / (sizeof( array[0] )) is good enough to get the size of the array. I guess the part ``` (sizeof( array[0] ) * (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*)) ``` is to avoid the whole thing divided by zero, anyone could help to explain? Thanks in advance. Cheers,

Original source