Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the default value of an array in C++?

Tags:

c++

arrays

If I were to create an array with int* array = new int[10]; and fill part of the array with values, how can I check how much of the array is filled? I want to loop through and check if each value is the default value but I'm not sure what the default value of each array element is. Would it be null 0 or garbage values?

like image 464
mysticalstick Avatar asked Oct 07 '16 04:10

mysticalstick


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 int array in C#?

int[] array = new int[5]; This array contains the elements from array[0] to array[4] . The elements of the array are initialized to the default value of the element type, 0 for integers.

What is the default data type of an array?

The array data type is a compound data type represented by the number 8 in the database dictionary. Arrays store a list of elements of the same data type accessed by an index (element) number.

Are arrays initialized in C?

An array can also be initialized using a loop. The loop iterates from 0 to (size - 1) for accessing all indices of the array starting from 0. The following syntax uses a “for loop” to initialize the array elements. This is the most common way to initialize an array in C.


1 Answers

This is how to set a default value in C++ when making an array.

int array[100] = {0};

Now every element is set to 0. Without doing this every element it garbage and will be undefined behavior if used.

Not all languages are like this. Java has default values when declaring a data structure but C++ does not.

like image 161
Gary Holiday Avatar answered Oct 08 '22 08:10

Gary Holiday