Search code examples
cpointerssyntaxstructurecompound-literals

How to use a member of a structure defined by a compound literal?


I´ve found this piece of code, which uses a pointer to a structure made by a compound literal:

int main()
{
   struct s {int i; int x;} *p;
   int j = 0;

   p = &((struct s){ j++ });
}

My questions are:

  • How is j++ a valid expression for modifying i and/or x and to what it get evaluated?
  • And how can I access the member i or x? Pointer offsets of p?

Solution

  • In a compound literal, any unspecified members get default-initialized, just like an initializer list for an object. So

    (struct s){ j++ })
    

    is equivalent to

    (struct s){ j++, 0 })
    

    j++ is the old value of j before j is incremented, just as in any other assignment. So this will set p->i = 0 and j = 1.

    You can access the members using pointer dereferencing.

    int x = p->x;
    int i = p->i;