How to assign a C struct inline?

前端 未结 2 1297
一个人的身影
一个人的身影 2021-02-02 05:32
typedef struct {
    int hour;
    int min;
    int sec;
} counter_t;

And in the code, I\'d like to initialize instances of this struct without explici

相关标签:
2条回答
  • 2021-02-02 06:08

    Initialization:

    counter_t c = {10, 30, 47};
    

    Assignment:

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

    The latter is called a "compound literal".

    0 讨论(0)
  • 2021-02-02 06:20

    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 @M.M 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;
    }
    
    0 讨论(0)
提交回复
热议问题