Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default value of a member in an array?

I instantiate an array like this:

int array[] = new int[4]; 

What are the default values for those four members? Is it null, 0 or not exists?

like image 474
dylanmensaert Avatar asked Mar 08 '13 17:03

dylanmensaert


People also ask

What is default value of an array?

When an array is created without assigning it any elements, compiler assigns them the default value. Following are the examples: Boolean - false. int - 0.

What is the default value of array in C?

For char arrays, the default value is '\0' . For an array of pointers, the default value is nullptr . For strings, the default value is an empty string "" . That's all about declaring and initializing arrays in C/C++.

What is the default value of an element of an array in Java?

Using default values in initialization of arrayFor double or float , the default value is 0.0 , and the default value is null for string.


1 Answers

It's 0. It can't be null, as null isn't a valid int value.

From section 7.6.10.4 of the C# 5 specification:

All elements of the new array instance are initialized to their default values (§5.2).

And from section 5.2:

The default value of a variable depends on the type of the variable and is determined as follows:

  • For a variable of a value-type, the default value is the same as the value computed by the value-type’s default constructor (§4.1.2).
  • For a variable of a reference-type, the default value is null.

Initialization to default values is typically done by having the memory manager or garbage collector initialize memory to all-bits-zero before it is allocated for use. For this reason, it is convenient to use all-bits-zero to represent the null reference.

(As an implementation detail, there's some trickiness around the first bullet point. Although C# itself doesn't allow you to declare a parameterless constructor for value types, you can create your own parameterless constructors for value types in IL. I don't believe those constructors are called in array initialization, but they will be called in a new X() expression in C#. It's outside the realm of the C# spec though, really.)

like image 126
Jon Skeet Avatar answered Sep 22 '22 06:09

Jon Skeet