Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to initialize a struct in accordance with C programming language standards

I need to instate a struct element, split in presentation and introduction. This is the thing that I have:
typedef struct MY_TYPE {
bool flag;
short int value;
double stuff;
} MY_TYPE;

void function(void) {
MY_TYPE a;
...
a = { true, 15, 0.123 }
}


Is this the best approach to announce and instate a local variable of MY_TYPE as per C programming language norms (C89, C90, C99, C11, and so forth)? Or then again is there anything better or possibly working?
by

2 Answers

rahul07
In (ANSI) C99, you can use a designated initializer to initialize a structure:

MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };

Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration."
RoliMishra
You can do it with a compound literal. According to that page, it works in C99 (which also counts as ANSI C).

MY_TYPE a;

a = (MY_TYPE) { .flag = true, .value = 123, .stuff = 0.456 };
...
a = (MY_TYPE) { .value = 234, .stuff = 1.234, .flag = false };


The designations in the initializers are optional; you could also write:

a = (MY_TYPE) { true,  123, 0.456 };
...
a = (MY_TYPE) { false, 234, 1.234 };

Login / Signup to Answer the Question.