noamgot noamgot - 3 months ago 7
C Question

intialize struct to zero except one field

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?

usr usr
Answer

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.