Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine the length of an array at compile time?

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

Update0

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.

like image 533
Matt Joiner Avatar asked Aug 02 '10 14:08

Matt Joiner


People also ask

Is the size of an array is determined at compile time?

An array is a collection of a fixed number of components hence the size of an array is determined at compile time.

How do you find the length of an array?

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.

What is determined at compile time?

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.

Can we give size of array at run time?

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.


2 Answers

(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.

like image 110
ndim Avatar answered Sep 22 '22 14:09

ndim


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.

like image 22
tibur Avatar answered Sep 21 '22 14:09

tibur