Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does array[100] = {0} set the entire array to 0?

How does the compiler fill values in char array[100] = {0};? What's the magic behind it?

I wanted to know how internally compiler initializes.

like image 872
Mahesh Avatar asked Mar 10 '09 05:03

Mahesh


People also ask

How do you initialize an entire array to zero 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 .

How do you assign a zero to all elements of an array in Java?

int arr[10] = {0}; ...to initialize all my array elements to 0.

Does Java automatically initialize arrays to zero?

Yes, for primitive types(except boolean and char) it will be default to ZERO.


2 Answers

It's not magic.

The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).

The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value.

Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:

char array[100] = {}; 

As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization

like image 169
bk1e Avatar answered Sep 26 '22 00:09

bk1e


Implementation is up to compiler developers.

If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.

like image 25
qrdl Avatar answered Sep 25 '22 00:09

qrdl