Search code examples
cstructzeroinitializer

In C, is there a way to make struct initialization of subobjects not initialize to zero?


Say I have a struct with an array inside it:

struct my_struct {
    // 128 will be enough for all of my use cases,
    // saves me from using malloc.
    double values[128]; 

    int value_count; 

    const char *info;
};

The C spec says about compound initializers:

6.5.2.5.14 102) For example, subobjects without explicit initializers are initialized to zero.

Meaning that if I zero initialize my struct, all of its 128 doubles will be initialized to zero. And if I explicitly initialize only the 3 first doubles, the remaining 125 doubles will be initialized to zero.

struct my_struct s = {
    // 3 values explicitly initialized,
    // the rest will be initialized to zero.
    .values = { 1.0, 2.0, 3.0 },

    .value_count = 3,

    .info = "sequence of reals",
};

I like the elegance of the designated initializer, but I don't like that I'm potentially wasting so much time clearing memory that I won't use. If I only care about the 3 first doubles, is there a way to make C not zero initialize the 125 remaining doubles? Should I avoid designated initializers if I don't want to waste cycles on memory clearing?


Solution

  • The C standard does not provide any feature to initialize some parts of an aggregate and not others in a definition. To give values to some parts and not others, simply assign the values separately:

    struct my_struct s;
    s.values[0] = 1.0;
    s.values[1] = 2.0;
    s.values[2] = 3.0;
    s.value_count = 3;
    s.info = "sequence of reals";
    

    It is just source code; there is no magic between setting initial values in the definition and setting them in assignments—if there were some way to set some initial values in the definition without clearing all other parts of the structure, it would have the same effect as the above source code.

    You can expect that some cycles will be expended clearing the 125 unused elements if the compiler cannot see that those elements are not used by subsequent code.