1
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.

JWpark
  • 15
  • 3

1 Answers1

3

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 };
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • 4
    However, this will assign *all* struct members, not a strict subset of struct members. – Ian Abbott Aug 09 '23 at 09:43
  • @IanAbbott Not really stated as a requirement in the question. In order to preserve some members, you'd have to do something like: `cookie = (Dog) { .color = "blue", .age = 12, .fur = cookie.fur };`. I think this should be ok in terms of assignment operator sequencing. – Lundin Aug 09 '23 at 09:47
  • 3
    I just thought it was worth pointing out as a caution for the uninitiated who might assume it was only assigning the named members. – Ian Abbott Aug 09 '23 at 09:53
  • If that's a common operation I'd still prefer an appropriate setter function… Otherwise biting the bullet and do two manual assignments appears preferable to me as well. – Aconcagua Aug 09 '23 at 09:56