5 ms·
There's nothing "C99" about that ARRAY_SIZE macro, of course. That said, I'm rather sceptical towards it, I think it's better written as-is. Otherwise, the qu
by unwind 12y ago
There's nothing "C99" about that ARRAY_SIZE macro, of course.
That said, I'm rather sceptical towards it, I think it's better written as-is.
Otherwise, the question "does SIZE mean bytes, or number of elements?" always arises to haunt me. Once you need to keep looking stuff like that up, the macro isn't helping.
In actual code, the name of the array never needs to be enclosed in parentheses so it's often clearer too. E.g. something like:
int fourk[4096];
for(size_t i = 0; i < sizeof fourk / sizeof *fourk; ++i)
...
I realize that it's not 100% DRY to repeat the array name, but I think it's a small price to pay for not having to use a non-standard macro that requires learning. It's all about friction.
- userbinator 12y agoI use the convention "size = number of bytes" (as in sizeof), "count = number of elements" and so my sizeof(x)/sizeof(x[0]) macro is actually called COUNT.
- clarry 12y agoIn the BSDs (and some other code bases) the macro is spelled nitems and is common enough to be considered idiomatic.
- kayamon 12y agoI always call mine "countof" to match the "sizeof" naming convention.
- noselasd 12y agohttps://msdn.microsoft.com/en-us/library/ms175773.aspx https://msdn.microsoft.com/en-us/library/ms175773.aspx - although I'm not sure it's a macro. The nice thing is it's detecting that you actually give it an array.
- TazeTSchnitzel 12y agoThe PHP language uses count() for array lengths. Maybe copying that and using ARRAY_COUNT() or such might be less ambiguous?
- AceJohnny2 12y agoI use that macro frequently but warily. The fact that it only works with static arrays and (AFAIK) the compiler won't warn you if you accidentally use it on dynamic arrays/pointers/array parameters is a big risk. Come to think of it, I'm afraid I'm leaving a time bomb for the next inexperienced maintainer who doesn't know the limitations.
- RustyRussell 12y agoSee the one I wrote for the Linux kernel; it will error at build time on a non-array (using tyoeof). Even better, grab it from CCAN: http://ccodearchive.net/info/array_size.html http://ccodearchive.net/info/array_size.html Cheers, Rusty.
- AceJohnny2 12y agoThanks! I see you use __builtin_types_compatible_p, which looks very useful but also appears to be a GCC-specific.