Loading lessons...
Omitting the Array Size
Omitting the Array Size
C++ can count for you. When you provide an initializer list, you don't have to write the size.
Let the compiler count
int nums[] = {10, 20, 30, 40, 50};
The compiler sees five values and creates exactly five slots. That's the same as writing int nums[5] = {...} - you just skipped the number.
Partially-filled arrays
You can also give a larger size and fewer initial values; the leftover slots become 0:
int nums[5] = {10, 20};
// result: {10, 20, 0, 0, 0}
The out-of-bounds risk
Whatever size an array has, its valid indexes run from 0 to length - 1. A 3-element array has indexes 0, 1, and 2 - and nothing else:
int nums[] = {10, 20, 30};
cout << nums[3]; // BAD: index 3 does not exist
Reading a slot that doesn't exist is undefined behavior. The program might print garbage, crash, or seem to work by luck. C++ does not check for you, so always stay in bounds.
TL;DR
- You may omit the size when the initializer is present:
int nums[] = {10, 20, 30};. - Giving a size with fewer values zero-fills the rest.
- Valid indexes go from 0 to
length - 1. - Out-of-bounds reads are undefined behavior - never rely on them.