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).
char a[MAGIC_STUFF(COMPLICATED(X, Z+FOO(G)))];
and not wanting to type that out again lower down. If the information is there and the toolset is there, use it.#define SEND_FIXED_COMMAND(cmd) send_command((arr), sizeof (arr))
so as to avoid having to specify both the name of the array and the name of a constant giving the array's size.