Skip to content
Related Articles
Open in App
Not now

Related Articles

C++ Omit Array Size

Improve Article
Save Article
  • Last Updated : 27 Nov, 2022
Improve Article
Save Article

Prerequisite: Array in C++ 

The array is a type of data structure that can store data of similar data types. The most significant feature is fixed size. There are two conditions by which we can check the initialization of the array.

Methods for Declaring Array 

1. Declaring size during initialization:

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

2. Omitting array size during initialization:

Here we are not declaring size while initializing the array.

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

The above examples do the same job. An array of size 5 gets created with the above elements inside of it. But there are certain differences between them:

  • In the first case, you are creating an array containing some element by implicitly declaring its size.
  • In the second case, you haven’t specified the array size, but you have inserted its values. Here, the compiler is able to determine the number of elements inserted and automatically creates an array of that size. But the user needs to maintain the size of the array implicitly.

Although, both methods are correct yet the method with size in it is considered better as the chances of error with the second method are more.

Example:

C++




// C++ program to demonstrate
// Methods of insertion in array
// with and without size
#include <iostream>
using namespace std;
  
int main()
{
    int arr1[] = { 1, 2, 3, 4, 5 };
  
    for (int i = 0; i < 5; i++)
        cout << arr1[i] << " ";
  
    cout << "\n";
  
    int arr2[5] = { 1, 2, 3, 4, 5 };
  
    for (int i = 0; i < 5; i++)
        cout << arr2[i] << " ";
  
    return 0;


Output:

1 2 3 4 5
1 2 3 4 5
My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!