C++ Omitting Array Size
In this page:
Omitting the Size at Initialization
When declaring an array and providing its initial values at the same time, the size inside the square brackets can be left empty, and the compiler counts the initializer values to determine the array's size.
Example: Omitting the Size at Initialization
#include <iostream>
int main() {
int arr[] = {1, 2, 3, 4, 5};
std::cout << "Size inferred as 5 elements" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Why This Works
The compiler can only infer an array's size when a complete list of initial values is provided at the moment of declaration, since it counts exactly how many values appear inside the braces.
Example: Why This Works
#include <iostream>
int main() {
int arr[] = {10, 20, 30}; // compiler counts 3 initializers
std::cout << sizeof(arr) / sizeof(arr[0]) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
When Size Cannot Be Omitted
The size cannot be omitted if the array is declared without any initializer values at all, since the compiler would then have nothing to count and needs an explicit size to reserve memory.
Example: When Size Cannot Be Omitted
#include <iostream>
int main() {
int arr[5]; // no initializer -- size must be given explicitly
arr[0] = 1;
std::cout << arr[0] << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Omitted Size with String Arrays
Omitting the size also works naturally when initializing an array of C-style strings, letting the compiler count how many string literals were provided.
Example: Omitted Size with String Arrays
#include <iostream>
#include <string>
int main() {
std::string names[] = {"Alice", "Bob", "Carol"};
for (int i = 0; i < 3; i++) {
std::cout << names[i] << " ";
}
std::cout << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Combining Omitted Size with a Partial Fill
Providing fewer initializer values than intended still infers a size matching only what was actually listed, so a partially intended array should state its size explicitly instead of relying on omission.
Example: Combining Omitted Size with a Partial Fill
#include <iostream>
int main() {
int arr[] = {1, 2}; // size inferred as 2, not larger
std::cout << sizeof(arr) / sizeof(arr[0]) << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- C++ Arrays Introduction
- C++ Looping Through Arrays
- C++ Omitting Array Size
- C++ Array Size
- C++ Multi-dimensional Arrays
- C++ Arrays & Functions
- C++ Strings (C-style)
- C++ std::string
- C++ String Concatenation
- C++ Converting Strings and Numbers
- C++ String Length
- C++ Accessing String Characters
- C++ using namespace std
- C++ String Methods
- C++ Array of Strings