Finding the size of a static array is a common operation. see: C find static array size - sizeof(a) / sizeof((a)[0])
This can be wrapped into a macro, eg:
#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))
however its possible to accidentally pass in a regular pointer.
eg: void func(SomeArray **foo) { int i = ARRAY_SIZE(foo); }
While its valid C, but often ends up being a logical error.
Its possible to prevent this mistake (taking advantage of per-processor to fail on a zero length bit-field).
#define ARRAY_SIZE(a) \
((sizeof(struct { int isnt_array : \
((const void *)&(a) == &(a)[0]); }) * 0) + \
(sizeof(a) / sizeof(*(a))))
I've found this macro works with GCC, but fails with Clang, for indirectly referenced members. with error: expression is not an integer constant expression
eg:
char word[8]; int i = ARRAY_SIZE(word);
ok.struct Bar { word[8]; }
void func(struct Bar *foo) { int i = ARRAY_SIZE(foo->word); }
fails.
Is there a more portable way to to implement this? (working with Clang is good of course though Im interested in general portability... other compilers too).
This seems such a common task that it would be good to have a re-usable portable macro.