6

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.

Craig McQueen
  • 41,871
  • 30
  • 130
  • 181
Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
  • See also SO question: [Is there a standard function in C that would return the length of an array?](http://stackoverflow.com/questions/1598773/is-there-a-standard-function-in-c-that-would-return-the-length-of-an-array) – Craig McQueen Mar 21 '11 at 00:14

4 Answers4

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

ndim
  • 35,870
  • 12
  • 47
  • 57
2

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.

tibur
  • 11,531
  • 2
  • 37
  • 39
  • 3
    isn't alignment just important for placing the array itself? Inside a c-array, the sizeof-division shall work. – nob Aug 02 '10 at 14:37
  • I think you're right: both sizeof will take alignment into consideration. So the sizeof(blah)/sizeof(type) should be safe. – tibur Aug 02 '10 at 14:46
1
    sizeof(array) / sizeof(int) 
mob
  • 117,087
  • 18
  • 149
  • 283
1

im not aware of a builtin that does this, but i recently used:

sizeof(array)/sizeof(array[0])

to do just that

trh178
  • 11,228
  • 5
  • 28
  • 37