Whether you use this method of getting the number of elements in an array or the more traditional sizeof method,
please encapsulate the logic in a macro.
Instead of writing either of these:
size_t length = sizeof array / sizeof array[0];
size_t length = (&array)[1] - array;
Define this macro instead:
#define countof( array ) ( sizeof(array) / sizeof((array)[0]) )
Or if you must:
#define countof( array ) ( (&(array))[1] - (array) )
And then you can just say:
size_t length = countof(array);
Edit: I used to call this macro 'elementsof', but it seems that 'countof' is a more common name for it and is a bit more clear too - so I'm going to run with that name in the future.
Instead of writing either of these:
Define this macro instead: Or if you must: And then you can just say: Edit: I used to call this macro 'elementsof', but it seems that 'countof' is a more common name for it and is a bit more clear too - so I'm going to run with that name in the future.