mindthief
mindthief

Reputation: 13393

How to assign a C struct inline?

typedef struct {
    int hour;
    int min;
    int sec;
} counter_t;

And in the code, I'd like to initialize instances of this struct without explicitly initializing each member variable. That is, I'd like to do something like:

counter_t counter;
counter = {10,30,47}; //doesn't work

for 10:30:47

rather than

counter.hour = 10;
counter.min = 30;
counter.sec = 47;

Don't recall syntax for this, and didn't immediately find a way to do this from Googling.

Thanks!

Upvotes: 74

Views: 90079

Answers (3)

Michael Lee
Michael Lee

Reputation: 336

As a complement to @MuhsinFatih's answer, and with more authoritative references.

We can use C99's Designator to achieve the goal, just like what @MuhsinFatih has suggested:

counter_t counter = {.hour = 10, .min = 30, .sec = 47};

The same rule applies to Array as well:

int num[5] = { [0]=123, [2]=456, [4]=789 };

printf("%d %d %d %d %d \n",num[0], num[1], num[2], num[3], num[4]);
// Output:
//    123 0 456 0 789 

Upvotes: 1

MuhsinFatih
MuhsinFatih

Reputation: 2231

For the sake of maintainability I prefer the list syntax WITH explicitly identified variables, as follows:

counter_t counter = {.hour = 10, .min = 30, .sec = 47};

or for returning inline for example:

return (struct counter_t){.hour = 10, .min = 30, .sec = 47};

I can imagine a scenario where one changes the order in which the variables are declared, and if you don't explicitly identify your variables you would have to go through all the code to fix the order of variables. This way it is cleaner and more readable

Upvotes: 52

Steve Jessop
Steve Jessop

Reputation: 279455

Initialization:

counter_t c = {10, 30, 47};

Assignment:

c = (counter_t){10, 30, 48};

The latter is called a "compound literal".

Upvotes: 115

Related Questions