Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to initialize an array?

Tags:

c++

Given an array map with size of 256, what is the best way to initialize it so that each element is false?

bool map[256];

for (int i=0; i<256; i++)
{
    map[i] = false;
}

Thank you

like image 620
q0987 Avatar asked Oct 30 '10 15:10

q0987


People also ask

What is the best possible way to initialize an array?

There are two ways to specify initializers for arrays: With C89-style initializers, array elements must be initialized in subscript order. Using designated initializers, which allow you to specify the values of the subscript elements to be initialized, array elements can be initialized in any order.

What is the best way to initialize an array in Visual Basic?

In visual basic, Arrays can be initialized by creating an instance of an array with New keyword. By using the New keyword, we can declare and initialize an array at the same time based on our requirements.

What is the correct way of initializing an array in C?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

What will happen if you do not initialize an array?

Even if you do not initialize the array, the Java compiler will not give any error. Normally, when the array is not initialized, the compiler assigns default values to each element of the array according to the data type of the element.


1 Answers

bool map[256] = { false };

edit: for a reference to the standard as to why this is legal, see the answers below.

like image 176
Idan K Avatar answered Nov 11 '22 16:11

Idan K