I can do this on initialization for a struct Foo:
Foo foo = {bunch, of, things, initialized};
but, I can't do this:
Foo foo; foo = {bunch, of, things, initialized};
So, two questions:
How can I do something similar to the second example, i.e. declare a bunch of variables for a struct in a single line of code after it's already been initialized? I'm trying to avoid having to do this for large structs with many variables:
Foo foo; foo.a = 1; foo.b = 2; foo.c = 3; //... ad infinitum
You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.
Accessing data fields in structs Although you can only initialize in the aggregrate, you can later assign values to any data fields using the dot (.) notation. To access any data field, place the name of the struct variable, then a dot (.), and then the name of the data field.
Try this:
Foo foo; foo = (Foo){bunch, of, things, initialized};
This will work if you have a good compiler (e.g. GCC). You might need to turn on C99 mode with --std=gnu99
, I'm not sure.
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