7

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?

3
  • I'm curious about this too, since std::size is constexpr in modern C++, it makes the impression to supersede sizeof. When should we still use sizeof instead std::size? What are the pros and cons? Commented Jan 20, 2022 at 23:18
  • 2
    @303: They're two different tools that ask two different questions. If you're uncertain of which to use, that is either because you don't understand the difference between those questions or you aren't sure which question you're trying to ask. Commented Jan 21, 2022 at 17:20
  • @NicolBolas Yeah, it has been a while since I've used sizeof and a quick search wouldn't have hurt. Not sure what I was asking exactly. "Move along, nothing to see here" :D Commented Jan 21, 2022 at 17:58

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.