Joakim
Joakim

Reputation: 165

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

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?

Upvotes: 5

Views: 5583

Answers (1)

zkoza
zkoza

Reputation: 2869

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

Upvotes: 11

Related Questions