how to assign multiple values into a struct at once?

前端 未结 6 1924
执笔经年
执笔经年 2020-12-02 13:15

I can do this on initialization for a struct Foo:

Foo foo =  {bunch, of, things, initialized};

but, I can\'t do this:

Foo f         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-02 13:38

    If you don't care too much about efficiency, you could double assign: i.e. create a new instance of the structure using aggregate initialization, and then copy it over:

    struct Foo foo;
    
    {
      struct Foo __tmp__ = {bunch, of, things, initialized};
      foo = __tmp__;
    }
    

    Make sure you keep the portion wrapped in {}s so as to discard the unnecessary temporary variable as soon as it's no longer necessary.

    Note this isn't as efficient as making, e.g., a 'set' function in the struct (if c++) or out of the struct, accepting a struct pointer (if C). But if you need a quick, preferably temporary, alternative to writing element-by-element assignment, this might do.

提交回复
热议问题