Last active
October 28, 2016 18:50
-
-
Save Bueddl/e9df95d15fee0263223e5432978e6248 to your computer and use it in GitHub Desktop.
Number of array elements (for static sized arrays)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
// C-Style way of obtaining number of elements in | |
// statically sized array. | |
// This is very unsafe! | |
#define SIZEOF_ARRAY(v) (sizeof(v)/sizeof(*v)) | |
// C++-ish way for obtaining the number of array elements. | |
// Safe, cannot be compiled for simple ptr (array-like) types. | |
template<class T, std::size_t N> | |
constexpr decltype(N) sizeof_array(const T(&)[N]) noexcept | |
{ | |
return N; | |
} | |
int main() | |
{ | |
const char arr_c[] = "Das ist ein Test!!!"; | |
int arr_i[] = {1, 2, 3, 4, 5}; | |
double arr_d[5]; | |
const char *test = arr_c; | |
std::cout << "sizeof(arr_c)=" << sizeof(arr_c) // gives 20 | |
<< ", sizeof_array(arr_c)=" << sizeof_array(arr_c) // gives 20 | |
<< ", SIZEOF_ARRAY(arr_c)=" << SIZEOF_ARRAY(arr_c) // gives 20 | |
<< std::endl | |
<< "sizeof(arr_i)=" << sizeof(arr_i) // gives 20 | |
<< ", sizeof_array(arr_i)=" << sizeof_array(arr_i) // gives 5 | |
<< ", SIZEOF_ARRAY(arr_i)=" << SIZEOF_ARRAY(arr_i) // gives 5 | |
<< std::endl | |
<< "sizeof(arr_d)=" << sizeof(arr_d) // gives 40 | |
<< ", sizeof_array(arr_d)=" << sizeof_array(arr_d) // gives 5 | |
<< ", SIZEOF_ARRAY(arr_d)=" << SIZEOF_ARRAY(arr_d) // gives 5 | |
<< std::endl | |
<< "sizeof(test)=" << sizeof(test) // gives 8 (not always expected) | |
<< ", sizeof_array(test)=" << sizeof_array(test) // safe: won't compile for non static sized array types | |
<< ", SIZEOF_ARRAY(test)=" << SIZEOF_ARRAY(test) // unsafe: gives 8 (!!!) | |
<< std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment