Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize struct to zero except one field

Tags:

c

struct

consider the following struct:

typedef struct _sampleStruct{
    bool b;
    int i;
    double d;
    int arr[10];
}sampleStruct;

I want to initialize a global instance of that struct such that b is initialized to true and rest of the fields are initialized to 0. in addition, I want the initialization to take place where I declare it, i.e I don't want to do something like that:

sampleStruct globalStruct = {0};

int someFunc()
{
    //...
    globalStruct.b = true;
    //...
}

is there a way to do that? I thought about doing something like that:

sampleStruct globalStruct = {.b = true, 0};

does it promise that all other fields are always zero?

like image 516
noamgot Avatar asked Sep 05 '16 10:09

noamgot


2 Answers

does it promise that all other fields are always zero?

Yes. The members that are not explicitly initialized will be zero initialized as part of the designated initializer. You don't even need that 0 there. This:

sampleStruct globalStruct = {.b = true};

should suffice.

like image 197
P.P Avatar answered Oct 01 '22 00:10

P.P


Yes, this is guaranteed by C11 6.7.9/21:

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

"Aggregate" is standard gibberish meaning: array or struct or union. As opposed to a plain, single value variable ("scalar").

In the above, "initialized as if it had static storage duration" means (6.7.9/10):

If an object that has static or thread storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
— if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;

This applies to all forms of initializers in an initializer list. Designated initializers is no exception nor special case.

like image 38
Lundin Avatar answered Sep 30 '22 22:09

Lundin