
Pointer vs array compile-time distinction (macros)
> I'm making a standard set of macros for our company, and would like to
> include
>
> #define ARRAY_LENGTH(array) (sizeof(array)/sizeof((array)[0]))
>
> for finding the length of a global or local static array.
> However, I am more or less certain that if I provide the macro without a
> check for whether something REALLY is an array, somebody will some day
> apply it to the parameter of a function. I can (partially) solve this
> through an assert(). However, I would really like a compile-time check.
> Can somebody make one?
That may not be possible.
What you need is a situation where an lvalue with array type is legal
but one with pointer type is not. Secondly you need to put that in the
context of an expression. The problem is that in most contexts the value
of an array in an expression is a pointer (to its first element) so whenever
that is the case it follows that a pointer is legal in that context.
The exceptions are when the array is the operand of sizeof or unary &.
I don't see sizeof being much usebecause you don't know anything about
the size of the object involved. & just gives you another pointer for both
pointer and array operands so you are no better off than you started.
> (If anybody need one to check that something really is a pointer, try
> either sizeof(array++), which should give a compile time error if applied
> to an array, with no side effects.)
Success of this doesn't guarantee you have a pointer (it could be an int
for instance). Failure doesn't guarantee you don't have a pointer (it could
be a const pointer or a pointer rvalue).
--
-----------------------------------------
-----------------------------------------