I assume this part is clear: sizeof( array ) / sizeof( array[0] )
This part (sizeof( array ) != sizeof(void*) || sizeof( array[0] ) <= sizeof(void*)) is a logical expression, so it returns true or false. When calculating the whole expression, therefore, multiplying sizeof( array[0] ) by the logical expression, the compiler converts the logical expression to 0 or 1. Thus, you get sizeof( array ) / (sizeof( array[0] ) * 1) or
sizeof( array ) / (sizeof( array[0] ) * 0) .
The first case is the normal and necessary case. The second case will give you a compiler error due to division by zero. Therefore, the code will not compile if you call, for example:
long *p;
But he will not catch errors, for example:
char *p; array_size(p);
And this does not compile for the case that I would like to compile for:
long x[1]; // assuming a platform with sizeof(long)==sizeof(void*) array_size(x);
BTW, if you declare this function as a macro (and in C ++ I really prefer a template style solution), you must change all array in the macro to (array) .
Werner henze
source share