Reputation: 461
In C language macro for getting number of array elements is well known and looks like this:
uint32_t buffer[10];
#define ARRAY_SIZE(x) sizeof(x)/sizeof(x[0])
size_t size = ARRAY_SIZE(buffer);
The question is, is there any universal macro for getting array elements or returning just one when it's used on variable ? I mean following usage of macro :
uint32_t buffer[10];
uint32_t variable;
#define GET_ELEMENTS(x) ???
size_t elements_of_array = GET_ELEMENTS(buffer); // returns 10
size_t elements_of_variable = GET_ELEMENTS(variable); // returns 1
Does anybody know the solution ?
I've edited my question because it was wrongly formulated, BTW I know that I can use :
sizeof(variable)/sizeof(uint32_t)
Question is how to combine it in one macro or maybe inline function is better solution ?
Upvotes: 0
Views: 675
Reputation: 73384
You could use sizeof
, like this:
#include <stdio.h>
int main(void)
{
unsigned int buffer[10];
// size of one unsigned int
printf("%zu\n", sizeof(unsigned int));
// this will print the number of elements of buffer * size of an unsigned int
printf("%zu\n", sizeof(buffer));
// you have a mistake
// the following printf() gives you the number of elements
printf("%d\n", sizeof(buffer)/sizeof(buffer[0]));
return 0;
}
Output (on my machine):
4
40
10
Regarding the edit you made:
You can't perform type checking in C, thus you can not check if what you pass is an array or a variable.
Upvotes: 3