← Back to C++ Course | Chapter 6: Arrays & Strings | Lesson 3 of 15

C++ Omitting Array Size

When an array is initialized with values at declaration, the size in the square brackets can be omitted entirely, and the compiler infers it automatically from the number of initializer values.

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

cpp
#include <iostream>

int main() {
	int arr[] = {1, 2, 3, 4, 5};
	std::cout << "Size inferred as 5 elements" << std::endl;
	return 0;
}

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

cpp
#include <iostream>

int main() {
	int arr[] = {10, 20, 30}; // compiler counts 3 initializers
	std::cout << sizeof(arr) / sizeof(arr[0]) << std::endl;
	return 0;
}

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

cpp
#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;
}

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

cpp
#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;
}

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

cpp
#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 run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.