How to assign a C struct inline?

C++CStruct

C++ Problem Overview


I have a struct

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!

C++ Solutions


Solution 1 - C++

Initialization:

counter_t c = {10, 30, 47};

Assignment:

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

The latter is called a "compound literal".

Solution 2 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmindthiefView Question on Stackoverflow
Solution 1 - C++Steve JessopView Answer on Stackoverflow
Solution 2 - C++MuhsinFatihView Answer on Stackoverflow