Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between std::size() vs sizeof() when determining array size

Tags:

c++

sizeof

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?

like image 614
Joakim Avatar asked Jun 15 '26 23:06

Joakim


1 Answers

  • 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:

  • https://en.cppreference.com/w/cpp/language/sizeof
  • https://en.cppreference.com/w/cpp/iterator/size

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.

like image 172
zkoza Avatar answered Jun 19 '26 02:06

zkoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!