C++

How to Fix “Array Must Be Initialized with a Brace Enclosed Initializer” Error in C++

In C++ to store the elements having same data types, arrays are normally used, which are defined as a cluster of elements that have the same data type and are assigned adjacent memory locations. Once an array is defined, its size remains constant, and its elements can be accessed using their indices. It makes it easy to store elements in a single array rather than calling them in different variables.

“Array Must Be Initialized with a Brace Enclosed Initializer” Error in C++

An array is initialized, and the first ten multiples are stored in it. When the program gets executed, it returns an “array must be initialized with a brace enclosed initializer” error that means there should be braces around the array:

#include <iostream>
using namespace std;

int main()
{

    int table_of_two[10]
        = 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 ;

    for (int i = 0; i < 10; i++)
{
        cout << table_of_two[i] << " ";
    }

    return 0;
}

 

The error is highlighted on the line#10 of the code.

How to Fix “Array Must Be Initialized with a Brace Enclosed Initializer” Error in C++

The syntax to initialize the array includes using curly braces as:

int array[10] = { 0 };

 
For multidimensional arrays, curly braces are used as:

int arr[array_size][array_size]= { { 0 } };

 
So, this error can be fixed by properly enclosing the elements of an array in curly braces.

#include <iostream>
using namespace std;

int main()
{
    int table_of_two[10]
        = { 2, 4, 6, 8, 10, 12, 14, 16, 18, 20 };

   
    for (int i = 0; i < 10; i++)
{
        cout << table_of_two[i] << " ";
    }

    return 0;
}

 

In this program, an array of the table of two is initialized, and it contains the first 10 multiples of 2. The use of a for loop is to keep the Integer i iterating until it reaches 10:


On the output, the array of the first ten multiples of two is returned.

Conclusion

An array in C++ is a cluster of elements that have the same data type and are assigned adjacent memory locations. It makes it easy to store elements in a single array rather than calling them in different variables. A common error is seen when arrays are being declared, that is, the “array must be initialized with a brace enclosed initializer”. This means that there must be braces around the array, missing braces lead to this error. This can be fixed by properly inserting braces around the arrays in the code.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.