Fernando
Fernando

Reputation: 21

Initialize array at compile time

foo is a global array of integers that must be initialized. If, in a future, I change SIZE to 6 then I will have to add MANUALLY two new INIT_VALUE items to the initialization list. Is there a macro or other thing that could be used to modify automatically the initialization list at compile time when the value of SIZE is changed?

#define SIZE 4
#define INIT_VALUE 101

/* global variable that must be initialized */
int foo[SIZE] = {INIT_VALUE, 
                 INIT_VALUE, 
                 INIT_VALUE, 
                 INIT_VALUE};

Upvotes: 1

Views: 2223

Answers (1)

MByD
MByD

Reputation: 137442

If this INIT_VALUE is not 0, you can't initialize the array in the way you mentioned (to support unknown elements). I don't think there's even such an option to implement it using macros, probably the correct way to do it is a loop to initialize (in function) the array (memset will not help either if your value doesn't look like 0xYXYXYXYX (all bytes are the same))

Upvotes: 1

Related Questions