C++ Omit Array Size

πŸ“¦ C++ Omit Array Size

In C++, you can omit (skip) the array size only when the array is initialized at the time of declaration.
The compiler automatically determines the size based on the number of elements.


πŸ”Ή 1. Basic Example (Size Omitted)

int arr[] = {10, 20, 30, 40};

βœ” Compiler sets the size to 4

Equivalent to:

int arr[4] = {10, 20, 30, 40};

πŸ”Ή 2. Accessing Elements

int arr[] = {5, 15, 25};

cout << arr[0]; // 5
cout << arr[2]; // 25


πŸ”Ή 3. Loop Through an Array with Omitted Size

int arr[] = {2, 4, 6, 8};

int size = sizeof(arr) / sizeof(arr[0]);

for (int i = 0; i < size; i++) {
cout << arr[i] << ” “;
}


πŸ”Ή 4. Character Array (String) Example

char name[] = "Cplusplus";

βœ” Size automatically includes the null character '\0'.


πŸ”Ή 5. Omit Size in 2D Arrays (Important Rule)

βœ” Allowed only for the first dimension

int matrix[][3] = {
{1, 2, 3},
{4, 5, 6}
};

❌ Not allowed (column size missing):

int matrix[][] = { {1,2}, {3,4} }; // error

πŸ”Ή 6. When You CANNOT Omit Array Size ❌

❌ Without Initialization

int arr[]; // error

❌ When Size Is Needed Later

int n = 5;
int arr[] = n; // error

πŸ”Ή 7. Use Case: Cleaner Code

int primes[] = {2, 3, 5, 7, 11};

βœ” Cleaner
βœ” Less error-prone
βœ” Easy to maintain


πŸ” Omitted Size vs Explicit Size

Omitted Size Explicit Size
Compiler decides size Programmer decides size
Must initialize Can initialize later
Cleaner syntax More control

πŸ“Œ Summary

  • Array size can be omitted only with initialization

  • Compiler counts elements automatically

  • In 2D arrays, omit only the first dimension

  • Not allowed without initialization

You may also like...