Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing an array of zeroes

It is well known that missing initializers for an array of scalars are defaulted to zero.

int A[5]; // Entries remain uninitialized int B[5]= { 0 }; // All entries set to zero 

But is this (below) guaranteed ?

int C[5]= { }; // All entries set to zero 
like image 417
Yves Daoust Avatar asked Aug 11 '16 09:08

Yves Daoust


People also ask

How do you initialize an array of zeros in Java?

Using default values in initialization of array For double or float , the default value is 0.0 , and the default value is null for string. Type[] arr = new Type[capacity]; For example, the following code creates a primitive integer array of size 5 . The array will be auto-initialized with a default value of 0 .

Can you initialize an array with 0 elements?

The array will be initialized to 0 in case we provide empty initializer list or just specify 0 in the initializer list. Designated Initializer: This initializer is used when we want to initialize a range with the same value.

What is the correct way of initialising an array?

The initializer for an array is a comma-separated list of constant expressions enclosed in braces ( { } ). The initializer is preceded by an equal sign ( = ). You do not need to initialize all elements in an array.


1 Answers

The empty braced initialisation performs aggregation-initialization of the array: this leads to zero-initialization of the int elements.

Yes, this is guaranteed.

like image 163
Bathsheba Avatar answered Sep 25 '22 04:09

Bathsheba