MachineElf
MachineElf

Reputation: 1281

reassign struct in C

I'm new to C and experimenting with structs. After I've created a struct, is it possible to reassign it with curly brackets?

typedef struct {
    int height;
    int age;
} Person;

int main (void)
{
    Person bill = {100,35};
    bill = {120,34}; // error: expected expression before ‘{’ token
    bill = Person {120,34}; // error: expected expression before ‘Person’

    return 0;
}

Upvotes: 5

Views: 1874

Answers (1)

Jens Gustedt
Jens Gustedt

Reputation: 78973

Not directly, but C99 has compound literals for that

bill = (Person){120,34};

you could even do things more readable by using designated initializers like

bill = (Person){ .height = 120, .age = 34, };

Upvotes: 11

Related Questions