Consider
int array[5]{};
std::cout << std::size(array) << std::endl;
This will give me the result of 5.
int array[5]{};
std::cout << sizeof(array) << std::endl;
This will give me the result of 20.
Why is that? What is the difference on size and sizeof?
std::size returns the number of array elements.sizeof is an operator that returns the number of bytes an object occupies in memory.In your case, an int takes 4 byres, so sizeof returns a value 4 times larger than std::size does.
References:
There is an old trick to compute the number of array elements using sizeof:
int arr[] = {1, 2, 3, 4, 5};
size_t arr_size = sizeof(arr)/sizeof(arr[0]);
but this should never be used in modern C++ instead of std::size.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With