Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a shorter way to find length of an array than this C code?

static int a[] = {1, 5, 645, 43, 4, 65, 5408, 4, 7, 90, 23, 11};
int len=sizeof(a)/sizeof(int);

Is there a shortcut, with ANSI 99?

like image 317
Caffeinated Avatar asked Jan 29 '26 14:01

Caffeinated


2 Answers

I think that there isn't a shortcut, but you cat use macro:

#define arrlen(arr) (sizeof(arr)/sizeof(arr[0]))
like image 71
asaelr Avatar answered Feb 01 '26 05:02

asaelr


Is there a shorter way to find length of an array than this C code?

Yes, one character shorter:

static int a[] = {1, 5, 645, 43, 4, 65, 5408, 4, 7, 90, 23, 11};
int len=sizeof a/sizeof(int);

edit: There's an even shorter version suggested by @pmg:

static int a[] = {1, 5, 645, 43, 4, 65, 5408, 4, 7, 90, 23, 11};
int len=sizeof a/sizeof*a;

You could also use fewer characters for the identifier len.

:)

like image 41
NPE Avatar answered Feb 01 '26 05:02

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!