Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array initialization at declaration

Tags:

arrays

c

I have a variable of type int array[10]. Is it possible to initialize only the last item of the array?

like image 576
Aravindh Avatar asked Apr 02 '14 00:04

Aravindh


People also ask

Can an array be initialized on declaration?

An array can also be initialized after declaration. Note: When assigning an array to a declared variable, the new keyword must be used.

Is it necessary to initialize array at the time of declaration?

It is necessary to initialize the array at the time of declaration. This statement is false.


1 Answers

Yes, using designated initializers (introduced in C99), you can write code like this:

int array[10] = {[9] = 42};

which is equivalent to:

int array[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 42};

This feature is also available in some compiler as an extension, for instance, GCC.

like image 196
Yu Hao Avatar answered Sep 21 '22 09:09

Yu Hao