It will depend on what initial value you want to assign to the values of that table and the type of them.
For the case that you expose in your example:
int a[10];
If you want to initialize to values 0 you have the following options:
Initialization by empty list
int a[10] {};
The array a
receives an empty list as the initial value, this empty list starts all its elements at the default value of the type of the array ( int
), in this case the value is 0
... so that all the elements of the array a
will get the value 0.
Initialization by empty list copy
int a[10] = {};
The array a
copy the elements of the list provided as the initial value, since this list is empty all its elements contain the default value of the type of the array ( int
), in this case the value 0
... so all the elements of the array a
will get the value 0.
The current compilers usually optimize this initialization so that the copy is omitted in most cases (performs an initialization of the value in situ being then equivalent to the initialization by empty list); however, the omission of copying in other more complex types is not guaranteed; whenever you have doubts about whether a list will be copied and you want to avoid such a copy: use Initialization by empty list.
Initialization in static space
static int a[10];
Static elements are initialized to the default value even when they are not assigned an initial value, so in the case of the static array a
all their elements contain the default value of the array type ( int
) , in this case the value 0
.
In the case of wanting to initialize values other than 0, it is more complicated:
Initialization by list
int a[10] { 1 };
The array a
receives a list as the initial value, this list contains a single element of the 10 that the array accepts ... what will happen is that the first element of the array will get the first value from the list and the rest of elements will be initialized to the default value of the type of the fix ( int
), which in this case will be 0
, this happens until filling all the values of the array:
int b[10] { 1, 1 }; // los 8 ultimos elementos contienen 0
int c[10] { 1, 1, 1, 1 }; // los 6 ultimos elementos contienen 0
int d[10] { 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // El ultimo elemento contiene 0
Initialization by list copy
int a[10] = { 1 };
Follow the same rules as the previous initialization but copying the list provided (copy that is usually omitted by the compiler). Therefore all the elements to which value has not been specified, will obtain the default value of the type of the fix ( int
), in this case the value 0
.
If you want to initialize a value different from the default value, you must specify the value for each of the elements to be initialized; if that is your choice, you can omit the size of the array and let the compiler deduce it for you:
int a[] {}; // Tamanyo 0!
int b[] { 1, 1 }; // Tamanyo 2
int c[] { 1, 1, 1, 1 }; // Tamanyo 4
int d[] { 1, 1, 1, 1, 1, 1, 1, 1, 1 }; // Tamanyo 9