Skip to content

Instantly share code, notes, and snippets.

@mooware
Last active December 14, 2015 17:58
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 mooware/5125494 to your computer and use it in GitHub Desktop.
Save mooware/5125494 to your computer and use it in GitHub Desktop.
Type-safe way to get the length of an array in C++.
// In C/C++, the idiom (sizeof(arr) / sizeof(*arr)) is often used to get the length of an array.
// But this will return incorrect results if arr is not actually an array, but a pointer.
// The following function template provides a type-safe way to get the length of an array,
// by "destructuring" the type and reading the array length from there.
#include <cstddef> // for size_t
template <typename T, size_t N>
constexpr size_t sizeof_array(T (&)[N])
{
return N;
}
// here is a fallback for compilers without support for constexpr:
// this function takes a reference to array of type T[N], and returns a reference to char.
// the return type is then used with sizeof() to get N (compare with MSVC's _countof).
template <typename T, unsigned int N> char (&_return_sizeof_array(T (&)[N]))[N];
#define sizeof_array(__arr__) sizeof(_return_sizeof_array((__arr__)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment