Pointer vs array compile-time distinction (macros) 
Author Message
 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).



Mon, 25 May 1998 03:00:00 GMT  
 [ 1 post ] 

 Relevant Pages 

1. arrays and pointers, char * vs. char [], distinction

2. Pointer vs array compile-time distiction

3. pointer to array vs pointer

4. Calculate array size at compile time

5. compile time constants in array declarations

6. Initializing an array during compile time?

7. Lists VS. Dynamic Arrays VS. Re-defining Arrays

8. pointer vs. array

9. array vs pointer

10. Case-switch vs. Array of function pointers

11. Dereferencing f-pointers, arrays of f-pointers, pointers to f-pointers


Powered by phpBB® Forum Software