Common array length macro for C? [duplicate]

Here’s a better C version (from Google’s Chromium project):

#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))

It improves on the array[0] or *array version by using 0[array], which is equivalent to array[0] on plain arrays, but will fail to compile if array happens to be a C++ type that overloads operator[]().

The division causes a divide-by-zero operation (that should be caught at compile time since it’s a compile-time constant expression) for many (but not all) situations where a pointer is passed as the array parameter.

See Is there a standard function in C that would return the length of an array? for more details.

There’s a better option for C++ code. See Compile time sizeof_array without using a macro for details.

Leave a Comment