Array-size macro that rejects pointers

Posted by nneonneo on Stack Overflow See other posts from Stack Overflow or by nneonneo
Published on 2013-10-18T15:07:21Z Indexed on 2013/10/18 15:54 UTC
Read the original article Hit count: 144

Filed under:
|
|

The standard array-size macro that is often taught is

#define ARRAYSIZE(arr) (sizeof(arr) / sizeof(arr[0]))

or some equivalent formation. However, this kind of thing silently succeeds when a pointer is passed in, and gives results that can seem plausible at runtime until things mysteriously fall apart.

It's all-too-easy to make this mistake: a function that has a local array variable is refactored, moving a bit of array manipulation into a new function called with the array as a parameter.

So, the question is: is there a "sanitary" macro to detect misuse of the ARRAYSIZE macro in C, preferably at compile-time? In C++ we'd just use a template specialized for array arguments only; in C, it seems we'll need some way to distinguish arrays and pointers. (If I wanted to reject arrays, for instance, I'd just do e.g. (arr=arr, ...) because array assignment is illegal).

© Stack Overflow or respective owner

Related posts about c

    Related posts about arrays