Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Init a struct in C

I have a question related to struct initialization in C. I have a struct:

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

I want a generic function/macro to initialize this struct and set the value of one parameter, eg status =1, easy way is:

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

However, by doing this I have set the value of status twice, first to 0 in init function and second set it to 1 (optimization does not help?).
(Please dont tell me t = {1,0,0} Im looking for a generic way)
I am thinking about a macro in 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 error "initialized field overwritten", because I have set the value of status twice.

Please help to point out how to alter the macro to achieve what I want, many thanks.

like image 243
Maluvel Avatar asked Nov 08 '13 21:11

Maluvel


2 Answers

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

should do it. The variable is then added in .data segment - as it is an initialized one - and all fields which are not mentionned explicitly are set to 0 by the compiler (instead of the linker or the loader).

like image 122
glglgl Avatar answered Oct 19 '22 23:10

glglgl


You have a space in the wrong place:

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

should do it.

The ( of the macro definition must come immediately after the macro name. Otherwise the parser takes this as a macro with no arguments and expands it to (param, value) ...etc... and in your case this then obviously is a syntax error.

Also note that it is usually a good idea to put () around parameters in the replacment text, to avoid syntax confusion.

like image 32
Jens Gustedt Avatar answered Oct 19 '22 23:10

Jens Gustedt