I want to initialize a struct element, split in declaration and initialization. This is what 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 way to declare and initialize a local variable of MY_TYPE
in accordance with C programming language standards (C89, C90, C99, C11, etc.)? Or is there anything better or at least working?
Update I ended up having a static initialization element where I set every subelement according to my needs.
Use Individual Assignment to Initialize a Struct in C Another method to initialize struct members is to declare a variable and then assign each member with its corresponding value separately.
An initializer for a structure is a brace-enclosed comma-separated list of values, and for a union, a brace-enclosed single value. The initializer is preceded by an equal sign ( = ).
No! We cannot initialize a structure members with its declaration, consider the given code (that is incorrect and compiler generates error).
You can't initialize any members in a struct declaration. You have to initialize the struct when you create an instance of the struct. struct my_struct { char* str; }; int main(int argc,char *argv[]) { struct my_struct foo = {"string literal"}; ... }
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." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)
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 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With