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

Viewed 649

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?

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:

EDIT

@303 asks "when should we still use sizeof instead of std::size? A short answer: never, especially in connection with "should". 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++.

Related