Sunday, November 30, 2014

Array initialization

Basic initialization
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
other syntax 
int myArray[10] = { [4] = 5, [2] = 5 }; 
is equivalent to
int myArray[6] = { 0, 0, 5, 0, 5, 0 };
initialize a range of elements to the same value
int myArray[10] = {[0 ... 9] = 5};
 
Elements with missing values will be initialized to 0:
int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...

So this will initialize all elements to 0:
int myArray[10] = { 0 }; // all elements 0(only for Zero initial)

Remember that objects with static storage duration will initialize to 0 if no initializer is specified:
static int myArray[10]; // all elements 0

In C++, an empty initialization list will also initialize every element to 0. This is not allowed with C:
int myArray[10] = {}; // all elements 0 in C++


And that "0" doesn't necessarily mean "all-bits-zero", so using the above is better and more portable than memset(). (Floating point values will be initialized to +0, pointers to null value, etc.)
Reference
[1] http://stackoverflow.com/questions/201101/how-to-initialize-an-array-in-c
[2] https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html
[3] http://www.lemoda.net/c/array-initialization/ (experiment)






No comments:

Post a Comment

Register Transfer Level Design with Verilog (1) [ebook]

設計程式之所以有趣不外乎是它的千變萬化,同樣的結果卻有不同的寫法。 但這些不同寫法當中也並沒有分誰對誰錯,也沒有制定標準來規範何事該用何解。 這也就是我們設計者的珍貴!! [1] Primitive Instantiations 在Verilog中最基本的邏輯...