Open In App

C++ Omit Array Size

Last Updated : 27 Nov, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads