Skip to content

Instantly share code, notes, and snippets.

@twoscomplement
Created December 18, 2018 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save twoscomplement/ab47f8e315664a05050779df4ae72e18 to your computer and use it in GitHub Desktop.
Save twoscomplement/ab47f8e315664a05050779df4ae72e18 to your computer and use it in GitHub Desktop.
A C++ macro to compute the number of elements in an array.
/*
ARRAY_SIZE(a)
A macro to compute the number of elements in an array a.
Features & considerations:
- Will not compile if a is not an array (error message is not elegant).
- Able to be used with non-const a.
- Happens to produce very few (false-positive) compile-time warnings with msvc 19 when
the result is used in signed and truncating arithmetic - unlike std::size()
(see also https://t.co/NvhjvMUhA1)
- Avoids these msvc compiler bugs:
https://developercommunity.visualstudio.com/content/problem/410617/sizeofchar-1-evaluates-to-0xffffffff.html
https://developercommunity.visualstudio.com/content/problem/410675/lambda-implicit-variable-capture-fails-near-value.html
- A revision of a pre-existing implementation used extensively in a large legacy codebase.
This version is written to avoid changes to existing code. YMMV :)
- Valid for C++ 98, 11, 14, and 17.
*/
namespace Detail
{
// No matching overloaded function found? Typically that error is produced when calling
// ARRAY_SIZE(a) where a is not an array.
template <typename T, size_t N> char ArrayHelper(const T(&)[N]);
}
// Returns the number of elements in the array 'a'
// Fails to compile unless 'a' is actually an array.
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(*a) * sizeof(Detail::ArrayHelper(a)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment