Initiate structure in C

I have a question related to initializing a structure in C. I have a structure:

struct TestStruct
{
u8 status;
u8 flag1;
u8 flag2;
};

I want the generic function / macro to initialize this structure and set the value of one parameter, for example status = 1, a simple way:

TestStruct t = {};
t.status = 1;

However, having done this, I set the status value twice, first to 0 in the init function, and the second set it to 1 (optimization does not help?).
(Please don't tell me t = {1,0,0} I'm looking for a general way)
I am thinking of a macro in the init function, something like:

#define INIT_TESTSTRUCT (param, value) \
{ .status=0, .flag1=0, .flag2=0, .param=value }
TestStruct t = INIT_TESTSTRUCT(status, 0);

However, the compiler gives the error “initialized field is overwritten”, because I set the status value twice.

Please help indicate how to modify the macro to achieve what I want, thanks a lot.

+4
3
#define INIT_TESTSTRUCT(param, value) \
    { .param=(value) }
TestStruct t = INIT_TESTSTRUCT(status, 0);

. .data, , , , 0 ( ).

+5

:

#define INIT_TESTSTRUCT(param, value) \
{ .status=0, .flag1=0, .flag2=0, .param=(value) }

.

( . (param, value) ...etc..., , , .

, () , .

+2

, -,

TestStruct t = {};

C. , .

TestStruct t = { 0 };

C. .

-, C- " " : , .

, , ,

TestStruct t = { .status = 1 };

. status 1, .

,

#define INIT_TESTSTRUCT(param, value) { .param = value }
TestStruct t = INIT_TESTSTRUCT(status, 1);

- .

+1
source

All Articles