简体   繁体   中英

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!

Initialization:

counter_t c = {10, 30, 47};

Assignment:

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

The latter is called a "compound literal".

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 I think

Side-note :

As @AshleyDuncan and @MM put, this feature was removed from ISO C++ after C99 https://stackoverflow.com/a/12122261/2770195 , but is supported in gnu c++.

So while you can do this just fine:

g++ -std=gnu++11 main.cpp -o main

This will throw an error if you try the example above:

# need an example. I was unable to find. Even clang++ supports it. If you know 
# one, please suggest an edit

If you need to compile with a C++ compiler with support for ISO C++11 or later that does not recognize this gnu extension, you may have to use a class with a simple constructor:

// backup workaround
// not cool
class gnuFTW {
public:
    int hour;
    int min;
    int sec;
    gnuFTW(int hour, int min, int sec) {
        this->hour = hour;
        this->min = min;
        this->sec = sec;
    }   
};

int main(int argc, const char * argv[]) {
    gnuFTW counter = gnuFTW(10,30,47);
    cout << counter.hour << endl;
    return 0;
}

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM