Get the number of elements with sizeof(a) / sizeof(a[0])
Divide the array's size by one element's size to count elements in C, and see why it returns the wrong answer inside a function that receives the array.
The element count of a C array is its total size divided by the size of one element. Wrapping that in a macro is idiomatic, and it works exactly where the compiler still knows the array's type. The trap is passing the array to a function, where the type quietly changes.
#include <stdio.h>
#define COUNT(a) (sizeof(a) / sizeof((a)[0]))
static void inside(int a[]) {
printf("in function: %zu\n", sizeof a / sizeof a[0]);
}
int main(void) {
int v[5] = {1, 2, 3, 4, 5};
printf("in main: %zu\n", COUNT(v));
inside(v);
return 0;
}in main: 5
in function: 2A parameter written as int a[] is really int *a. In the function, sizeof a is the size of a pointer, 8 bytes on x86-64 Linux, and sizeof a[0] is 4, so the division gives 2, a plausible-looking wrong number with no diagnostic from the language. GCC 14 does warn about this with -Wsizeof-array-argument, which is part of -Wall. The decay rule is in the C23 draft, section 6.7.6.3. Pass the count as a separate parameter, and use the macro only on a real array object, never on a pointer or on a function parameter.