cstructurecoding-efficiency

How to edit multiple variables inside a structure in C


typedef struct
{
   string color;
   int age;
}Dog;


int main(void)
{
    Dog cookie = ("brown", 6);
    cookie.color = "blue";
    cookie.age = 12;
}

Hello, I'd like to know if there's a way to edit multiple structure values as such, while only using a single line instead of repeating "structName.varName" over and over.

Would there be a similar method for changing multiple values for objects in C as well? Thank you so much.


Solution

  • You can assign multiple struct members a value at once, by using a compound literal temporary object:

    cookie = (Dog) { "blue", 12 };
    

    Or for increased readability, combine this with designated initializers (equivalent code):

    cookie = (Dog) { .color = "blue", .age = 12 };