Your use of the macro expands to something like sizeof (sizeof ....)
. Since the result of sizeof
is a size_t
, you're getting sizeof (size_t)
, which is evidently 8 on your platform.
You probably wanted
printf("%zu\n", TOTAL_ELEMENTS);
(Note that %d
is the wrong conversion specifier for a size_t
, and a good compiler will at least warn about your version.)
Here's a complete program that works:
#include <stdio.h>
int main()
{
int array[] = {23,34,12,17,204,99,16};
size_t const TOTAL_ELEMENTS = (sizeof array) / (sizeof array[0]);
printf("%zu\n", TOTAL_ELEMENTS);
}
Output:
7
Note that I made TOTAL_ELEMENTS
be an ordinary object, as there's no need for it to be a macro here. You may need it as a macro if you want a version that will substitute the array name, like this:
#define TOTAL_ELEMENTS(a) (sizeof (a) / sizeof (a)[0])
You'd then write:
printf("%zu\n", TOTAL_ELEMENTS(array));