Comment

Comment by Stratoscope

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.
parent Stratoscope 10 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton