Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign multiple values into a struct at once?

Tags:

c++

c

struct

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:

  1. Why can't I do the latter, is the former a special constructor for initialization only?
  2. 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 
like image 254
jim Avatar asked Feb 13 '12 23:02

jim


People also ask

Can you assign multiple variables at once?

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.

Can you assign values in a struct?

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.


1 Answers

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.

like image 148
David Grayson Avatar answered Sep 21 '22 08:09

David Grayson