Search code examples
cassignment-operatorc11aggregate-initializationcompound-literals

Given a pointer to a structure, can I assign the structure the result of an aggregate-initializer in one line?


For example, given a structure S:

typedef struct {
  int a, b;
} S;

... and a method which takes a pointer to S, can I assign it the value of an aggregate initializer1 all in one line? Here's my existing solution which uses a temporary:

void init_s(S* s) {
  S temp = { 1, 2 };
  *s = temp;
}

I'm using C11.


1 For the very rare super-pedant who doesn't understand my question because somehow "aggregate initializer" wouldn't apply here because the LHS is not declaring a new object, I mean "aggregate-initializer-like syntax with the braces and stuff".


Solution

  • Yes, you can using the compound literals syntax:

    #include <stdio.h>
    
    typedef struct {
      int a, b;
    } S;
    
    int main(void) {
        S s;
        S *p = &s;
    
        *p = (S){1,2};
    
        printf("%d %d\n", p->a, p->b);
        return 0;
    }
    

    Demo