Are there macros or builtins that can return the length of arrays at compile time in GCC?
For example:
int array[10];
For which:
sizeof(array) == 40
???(array) == 10
I might just point out that doing this in C++ is trivial. One can build a template that returns the number inside []
. I was certain that I'd once found a lengthof
and dimof
macro/builtin in the Visual C++ compiler but cannot find it anymore.
An array is a collection of a fixed number of components hence the size of an array is determined at compile time.
array.length: length is a final variable applicable for arrays. With the help of the length variable, we can obtain the size of the array. Examples: int size = arr[].length; // length can be used // for int[], double[], String[] // to know the length of the arrays.
Compile-time is the time at which the source code is converted into an executable code while the run time is the time at which the executable code is started running.
Thus the size of the array is determined at the time of its creation or, initialization once it is done you cannot change the size of the array. Still if you try to assign value to the element of the array beyond its size a run time exception will be generated.
(sizeof(array)/sizeof(array[0]))
Or as a macro
#define ARRAY_SIZE(foo) (sizeof(foo)/sizeof(foo[0]))
int array[10];
printf("%d %d\n", sizeof(array), ARRAY_SIZE(array));
40 10
Caution: You can apply this ARRAY_SIZE()
macro to a pointer to an array and get a garbage value without any compiler warnings or errors.
I wouldn't rely on sizeof since aligment stuff could mess up the thing.
#define COUNT 10
int array[COUNT];
And then you could use COUNT as you want.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With