how to assign multiple values into a struct at once?

c, c++, struct

Solution

The first is an aggregate initializer - you can read up on those and tagged initializers at this solution:

What is tagged structure initialization syntax?

It is a special initialization syntax, and you can't do something similar after initialization of your struct. What you can do is provide a member (or non-member) function to take your series of values as parameters which you then assign within the member function - that would allow you to accomplish this after the structure is initialized in a way that is equally concise (after you've written the function the first time of course!)

Problem

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: - Why can't I do the latter, is the former a special constructor for initialization only? 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 ```

Original source

Related problems