How to find size of an array in C without sizeof
Whether you use this method of getting the number of elements in an array or the more traditional sizeof method, <i>please</i> encapsulate the logic in a macro.<p>Instead of writing either of these:<p><pre><code>  size_t length = sizeof array / sizeof array[0];

  size_t length = (&array)[1] - array;
</code></pre>
Define this macro instead:<p><pre><code>  #define countof( array )  ( sizeof(array) / sizeof((array)[0]) )
</code></pre>
Or if you must:<p><pre><code>  #define countof( array )  ( (&(array))[1] - (array) )
</code></pre>
And then you can just say:<p><pre><code>  size_t length = countof(array);
</code></pre>
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.