Skip to main content
Back to Blog
Programming LanguagesWeb Development
14 August 20263 min readUpdated 14 August 2026

Understanding Array Sizes in C++

C++ Array Sizes Determining the Size of an Array To find out the size of an array in C++, the operator is invaluable. You might wonder why an array with 5 elements shows a size...

Understanding Array Sizes in C++

C++ Array Sizes

Determining the Size of an Array

To find out the size of an array in C++, the sizeof() operator is invaluable. You might wonder why an array with 5 elements shows a size of 20. This is because sizeof() returns the size in bytes, not the number of elements. Since an int typically occupies 4 bytes, the total size of the array becomes 4 bytes x 5 elements = 20 bytes.

To calculate the number of elements in an array, divide the total size of the array by the size of an individual element. This technique gives you the actual count of elements.

Iterating Through an Array with sizeof()

In earlier lessons, arrays were looped using a fixed size condition like i < 5. This method is not ideal for arrays of different sizes. Instead, using sizeof() allows for more adaptable looping structures, making your code more robust and flexible.

Rather than hardcoding the loop size, it's better to employ:

int nums[5] = {10, 20, 30, 40, 50};
int getArrayLength = sizeof(nums) / sizeof(nums[0]);
for (int i = 0; i < getArrayLength; i++) {
    cout << nums[i] << endl;
}

C++ 11 introduced the range-based "for-each" loop, which offers an even cleaner approach to iterating over arrays.

Understanding these different looping methods is crucial, as various programs may use one approach over the other.