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.
You've almost got it...
Quick search on 'struct initialize c' shows me this
I didn't like any of these answers so I made my own. I don't know if this is ANSI C or not, it's just GCC 4.2.1 in it's default mode. I never can remember the bracketing so I start with a subset of my data and do battle with compiler error messages until it shuts up. Readability is my first priority.
The data may start life as a tab-delimited file that you search-replace to massage into something else. Yes, this is Debian stuff. So one outside pair of {} (indicating the array), then another pair for each struct inside. With commas between. Putting things in a header isn't strictly necessary, but I've got about 50 items in my struct so I want them in a separate file, both to keep the mess out of my code and so it's easier to replace.
I've been looking for a nice way to initialize my struct, and I've got to using the below (C99). This lets me initialize either a single structure or an array of structures in the same way as plain types.
This can be used in the code as:
In (ANSI) C99, you can use a designated initializer to initialize a structure:
Edit: 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)
If MS has not updated to C99, MY_TYPE a = { true,15,0.123 };
as Ron Nuni said:
An important thing to remember: at the moment you initialize even one object/variable in the struct, all of its other variables will be initialized to default value.
If you don't initialize the values in your struct (i.e. if you just declare that variable), all
variable.members
will contain "garbage values", only if the declaration is local!If the declaration is global or static (like in this case), all uninitialized
variable.members
will be initialized automatically to:0
for integers and floating point'\0'
forchar
(of course this is just the same as0
, andchar
is an integer type)NULL
for pointers.