Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialise all elements in an array with a value using compound literals

Tags:

arrays

c

gcc

c99

gcc4

float myArray[myArraySize] = {1};

In the expression above only the first element is init with 1. How can you init all the elements with a value using a compound literals(not memset)?

I'm using GCC 4.2 on unix to compile.

like image 535
Rad'Val Avatar asked Oct 25 '11 18:10

Rad'Val


2 Answers

This

float myArray[100] = {[0 ... 99] = 1.0};

is how you do it.

See Designated Initializers in the GCC docs which says:

To initialize a range of elements to the same value, write `[first ... last] = value'.

like image 161
Bee San Avatar answered Oct 01 '22 04:10

Bee San


No, only the first element will be initialized to 1.0. The rest will be initialized, but to 0.0 per the C standard. Have a look at the C faq for some more examples.

like image 43
Michael Goldshteyn Avatar answered Oct 01 '22 04:10

Michael Goldshteyn